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

220. Contains Duplicate III

2016-08-06 23:36 295 查看
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.

题意:

求数组中是否存在两个数其下标差不大于k,数值差不大于t。

思路:

使用map数据结构来解,用来记录数字和其下标之间的映射。 这里需要两个指针i和j,刚开始i和j都指向0,然后i开始向右走遍历数组,如果i和j之差大于k,则删除并j加1。这样保证了m中所有的数的下标之差都不大于k,然后用map数据结构的lower_bound()函数来找一个特定位置,就是大于或等于nums[i] - t的地方,所有下标小于这个位置的数和nums[i]的差的绝对值会大于t 。然后检测该位置上的数字,如果差小于等于t,则返回true。最后遍历完整个数组返回false。

class Solution {
public:
bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
map<int, int> m;
int j = 0;
for (int i = 0; i < nums.size(); ++i) {
if (i - j > k) m.erase(nums[j++]);
auto a = m.lower_bound(nums[i] - t);
if (a != m.end() && a->first - nums[i] <= t) return true;
m[nums[i]] = i;
}
return false;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: