Clairezz_的博客

Never give up!

[leetcode][hash] Contains Duplicate II

题目:

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;
}
};


阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

[leetcode][hash] Contains Duplicate II

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭