您的位置:首页 > 大数据 > 人工智能

[leetcode]220. Contains Duplicate III

2017-07-30 20:20 323 查看
题目链接:https://leetcode.com/problems/contains-duplicate-iii/description/

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.

class Solution {
public:
bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
long long t_long=t;
set<long long> window; // set is ordered automatically
for (int i = 0; i < nums.size(); i++) {
if (i > k) window.erase((long long)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 long)(nums[i] - t_long)); // x-nums[i] >= -t ==> x >= nums[i]-t
// x - nums[i] <= t ==> |x - nums[i]| <= t
if (pos != window.end() && *pos <= (long long)(t_long+nums[i])) return true;
window.insert((long long)nums[i]);
}
return false;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: