Given an array of integers, find out whether there is II distinct indices i and J in the array such th At the absolute difference between nums[i] and Nums[j] are at most T and the absolute difference between I and J are at the most K.
Find out whether the array has a maximum distance of K, while the maximum difference is two number of T. 1, the first time out, with a very stupid method, put into the ArrayList, but because of the special point, to use a long type, and then each need to sort, so decisively timed out.
Public classSolution { Public BooleanContainsnearbyalmostduplicate (int[] Nums,intKintt) {if(T < 0 | | K < 1){ return false; } if(k > Nums.length-1) {k= Nums.length-1; } ArrayList<Long> list =NewArrayList (); for(inti = 0; I <= K; i++) {List.add (Long) nums[i]); } collections.sort (list); for(inti = 1; I < list.size (); i++){ if(List.get (i)-List.get (i-1) <=t) { return true; } } for(inti = k + 1; i < nums.length; i++) {List.remove (Long) Nums[i-k-1]); List.add ((Long) nums[i]); Collections.sort (list); for(intj = 1; J < List.size (); J + +){ if(List.get (j)-List.get (j-1) <=t) { return true; } } } return false; }}
2, with a map implementation, similar to the principle of bucket sequencing, first turn the data into positive numbers, and the use of long (otherwise error, such as 2 and 2 divided by 3 equals 0, but 4 is greater than 3), while the bucket (t) = t + 1 (t = = 0 of the case to be discharged)
Public classSolution { Public BooleanContainsnearbyalmostduplicate (int[] Nums,intKintt) {if(K < 1 | | T < 0){ return false; } HashMap<long, long> map =NewHashMap (); for(inti = 0; i < nums.length; i++){ Longpos = (Long) Nums[i]-Integer.min_value; Longnum = 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) { LongDelete = ((Long) Nums[i-k]-Integer.min_value)/((Long) T + 1); Map.Remove (delete); } map.put (num, POS); } return false; }}
Leetcode 220. Contains Duplicate III asks an array for elements that are not required----------Java