217. Contains Duplicate
Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.
public class Solution {
public boolean containsDuplicate(int[] nums) {
Arrays.sort(nums);
for(int i=0; i<nums.length-1; i++) {
if(nums[i] == nums[i+1])
return true;
}
return false;
}
}
219. Contains Duplicate II
Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j]and the difference between i and j is at most k.
public class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
Map<Integer, Integer> p = new HashMap<Integer, Integer>();
for(int i=0; i<nums.length; i++) {
if(p.containsKey(nums[i])) {
if(i - p.get(nums[i]) <= k)
return true;
}
p.put(nums[i], i);
}
return false;
}
}
220. Contains Duplicate III
Given an array of integers, find out whether there are two distinct indices i and j in the array such that the difference between nums[i] andnums[j] is at most t and the difference between i and j is at most k.
注意treeset,treemap对重复的key都是覆盖的
但是在这题里面问题不大
import java.util.TreeSet;
/*
* 使用自带的TreeSet可能里面的算法已经优化好了
*/
public class Solution {
public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
// 只有TreeSet有floor,ceiling方法,所以reference也要指定为TreeSet,不能直接写Set
TreeSet<Integer> set = new TreeSet<Integer>();
// HashSet<Integer> set = new HashSet<Integer>();
for(int i=0; i<nums.length; i++) {
Integer floor = set.floor(nums[i] + t);
Integer ceil = set.ceiling(nums[i] - t);
if((floor != null && floor >= nums[i]) ||
(ceil != null && ceil <= nums[i]))
return true;
set.add(nums[i]);
if(set.size() > k)
set.remove(nums[i - k]);
}
return false;
}
}
The idea is like the bucket sort algorithm. Suppose we have consecutive buckets covering the range of nums with each bucket a width of (t+1). If there are two item with difference <= t, one of the two will happen:
(1) the two in the same bucket
(2) the two in neighbor buckets
def containsNearbyAlmostDuplicate(self, nums, k, t):
if t < 0: return False
n = len(nums)
d = {}
w = t + 1
for i in xrange(n):
m = nums[i] / w
if m in d:
return True
if m - 1 in d and abs(nums[i] - d[m - 1]) < w:
return True
if m + 1 in d and abs(nums[i] - d[m + 1]) < w:
return True
d[m] = nums[i]
if i >= k: del d[nums[i - k] / w]
return False