首页 > 代码库 > leetcode 220. Contains Duplicate III 求一个数组中有没有要求的元素 ---------- java
leetcode 220. Contains Duplicate III 求一个数组中有没有要求的元素 ---------- java
Given an array of integers, find out whether there are two distinct indices i and j in the array such that the absolute difference between nums[i] and nums[j] is at most t and the absolute difference between i and j is at most k.
找出数组中有没有最多相距k,同时最大相差t的两个数。
1、第一次超时,用了很笨的办法,放入ArrayList中,但是由于特殊点,要用Long类型,然后每一次都需要排序,所以果断超时了。
public class Solution { public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) { if (t < 0 || k < 1){ return false; } if (k > nums.length - 1){ k = nums.length - 1; } ArrayList<Long> list = new ArrayList(); for (int i = 0; i <= k; i++){ list.add((long)nums[i]); } Collections.sort(list); for (int i = 1; i < list.size(); i++){ if (list.get(i) - list.get(i - 1) <= t){ return true; } } for (int i = k + 1; i < nums.length; i++){ list.remove((long)nums[i - k - 1]); list.add((long)nums[i]); Collections.sort(list); for (int j = 1; j < list.size(); j++){ if (list.get(j) - list.get(j - 1) <= t){ return true; } } } return false; } }
2、用map实现,类似于桶排序的原理,首先把数据都转成正数,并且使用long型(否则会出错,比如-2和2除以3都等于0,但是相距4大于3),同时桶(t) = t + 1(t == 0的情况要排出)
public class Solution { public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) { if (k < 1 || t < 0){ return false; } HashMap<Long, Long> map = new HashMap(); for (int i = 0; i < nums.length; i++){ long pos = (long) nums[i] - Integer.MIN_VALUE; long num = pos / ((long) t + 1); if (map.containsKey(num) || (map.containsKey(num - 1) && Math.abs(map.get(num - 1) - pos) <= t) || (map.containsKey(num + 1) && Math.abs(map.get(num + 1) - pos) <= t)){ return true; } if (map.size() >= k){ long delete = ((long) nums[i - k] - Integer.MIN_VALUE) / ((long) t + 1); map.remove(delete); } map.put(num, pos); } return false; } }
leetcode 220. Contains Duplicate III 求一个数组中有没有要求的元素 ---------- java
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。