220. Contains Duplicate III

 

 因为测试加入了int边界的数所以答案一直通不过 改成long类型就可以了

 

 自己写的跟答案思路一样 过程一样 就是没法通过 第一段是自己的 第二段是答案的思路

class Solution {
public:
bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
set<long> iset;
if(k <= 0 || t < 0 || nums.size() <= 1)
return false;
for(int i = 0; i < nums.size(); ++i) {
if(i > k) iset.erase(nums[i - k - 1]);
auto it = iset.lower_bound((long)nums[i] - t);
if(it != iset.end() && (*it - (long)nums[i] <= t));
return true;
iset.insert((long)nums[i]);
}
return false;
}
};

 

 

bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
set<long> window; // set is ordered automatically
for (int i = 0; i < nums.size(); i++) {
if (i > k) window.erase(nums[i-k-1]); // keep the set contains nums i j at most k
// |x - nums[i]| <= t ==> -t <= x - nums[i] <= t;
auto pos = window.lower_bound((long)nums[i] - t); // x-nums[i] >= -t ==> x >= nums[i]-t
// x - nums[i] <= t ==> |x - nums[i]| <= t
if (pos != window.end() && (*pos - (long)nums[i] <= t))
return true;
window.insert((long)nums[i]);
}
return false;
}

posted on 2017-09-15 22:54  bloomingFlower  阅读(81)  评论(0编辑  收藏  举报