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

Leetcode 220. Contains Duplicate III

2018-02-28 15:21 381 查看
原题:
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.

解决方法:
定义一个set,用其保存数组中的最近k个数,然后从中找符合要求的目标数,如果有,则返回true。

代码:
bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
set<long> s;
for(int i = 0; i < nums.size(); i++){
if ( i > k)
s.erase(nums[i-k-1]);
auto it = s.lower_bound((long)nums[i] - t);
if (it != s.end() && (*it - nums[i]) <= t)
return true;

s.insert(nums[i]);
}
return false;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  cplusplus Leetcode