原题
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 absolute difference between i and j is at most k.
代码实现
public bool ContainsNearbyDuplicate(
int[] nums,
int k)
{
Dictionary<
int,
int> dict =
new Dictionary<
int,
int>();
for (
int i =
0; i < nums.Length; i++)
{
if (dict.ContainsKey(nums[i]))
{
if (Math.Abs(i - dict[nums[i]]) <= k)
return true;
dict.Remove(nums[i]);
dict.Add(nums[i], i);
continue;
}
dict.Add(nums[i], i);
}
return false;
}