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

[leetcode][hash] Contains Duplicate II

2015-07-08 15:46 561 查看
题目:

Given an array of integers and an integer k,
find out whether there there are two distinct indices i and j in
the array such that nums[i] = nums[j] and
the difference between iand j is
at most k.

维护一个长度为k的窗口

class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
if (nums.size() < 2 || k <= 0) return false;
int start = 0, end = 0;
set<int> hashTable;
hashTable.insert(nums[0]);
for (int i = 1; i < nums.size(); ++i){
set<int>::iterator iter = hashTable.find(nums[i]);
if (iter != hashTable.end()) return true;
hashTable.insert(nums[i]);
end = i;
if (end - start == k){
hashTable.erase(nums[start]);
++start;
}
}
return false;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: