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.
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
int len = nums.size();
if (len <= 1){
return false;
}
unordered_set<int> s;
for (int i : nums){
if (s.count(i)){
return true;
}
else{
s.insert(i);
}
}
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.最初想法是用map<int,vector<int>>记录值和相应的索引,最后发现没有必要啊,i从0遍历到len-1是依次增大的,记录某值最大的i即可。
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
map<int, int> m;
int len = nums.size();
for (int i = 0; i < len; i++){
if (m.count(nums[i])){
if (i - m[nums[i]] <= k){
return true;
}
}
m[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] and nums[j] is at most t and the difference between i and j is at most k.
class Solution {
public:
bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
int len = nums.size();
for (int i = 0; i < len; i++){
for (int j = i + 1; j <= i + k && j < len; j++){
long long a = nums[i];
long long b = nums[j];
long long diff = a>b ? (a - b) : (b - a);
if (diff <= t){
return true;
}
}
}
return false;
}
};
超时
下面有一巧妙的算法:
1.首先维持一个大小为k的multiset,即相当于滑动窗口;
2.对于nums[i],找窗口中 p=ms.lower_bound(nums[i] - t) ,即是不小于nums[i] - t的数的迭代器;
3.*p可能不存在,有可能小于nums[i],也有可能大于nums[i];
小于时,存在即可返回true;
大于时,*p-nums[i]<=t 即可返回true
所以总的判断
if (p != ms.end()&& *p-nums[i]<=t)
class Solution {
public:
bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
int len = nums.size();
multiset<long long> ms;
for (int i = 0; i < len; i++){
if (ms.size()>k){
ms.erase(nums[i - k - 1]);
}
auto p = ms.lower_bound(nums[i] - t);
if (p != ms.end()&& *p-nums[i]<=t){
return true;
}
ms.insert(nums[i]);
}
return false;
}
};