# 题目

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

# AC代码

class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
if (nums.empty())
return false;

int sz = nums.size();
//使用容器unordered_set 其查找性能为常量
unordered_set<int> us;
int start = 0, end = 0;
for (int i = 0; i < sz; ++i)
{
if (us.count(nums[i]) == 0)
{
us.insert(nums[i]);
++end;
}
else{
return true;
}

if (end - start > k)
{
us.erase(nums[start]);
++start;
}
}//for
return false;

}
};


GitHub测试程序源码

#### leetcode 219: Contains Duplicate II

2015-05-29 15:02:09

#### 219. Contains Duplicate II [easy] (Python)

2016-06-14 19:59:14

#### 【LeetCode-面试算法经典-Java实现】【219-Contains Duplicate II（包含重复元素II）】

2015-08-29 06:36:21

#### LeetCode 219:Contains Duplicate II

2015-05-31 18:41:22

#### [leetcode-219]Contains Duplicate II（Ｃ）

2015-08-26 11:03:54

#### leetcode【217+219 Contains Duplicate I+II】【python】

2016-09-08 10:33:49

#### leetcode笔记：Contains Duplicate II

2016-02-24 18:31:03

#### LeetCode219 ContainsDuplicateII java题解

2015-07-02 17:50:06

#### Contains Duplicate II - LeetCode 219

2015-06-01 22:40:35

#### leetcode: (219) Contains Duplicate II

2015-08-28 20:50:16