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 class Solution {
public bool ContainsNearbyDuplicate(int[] nums, int k) {
Dictionary<int, int> dict = new Dictionary<int, int>();
for (int i = 0; i < nums.Length; i++) {
int index;
if (dict.TryGetValue(nums[i], out index)) {
if (i - index <= k) {
return true;
}
}
dict[nums[i]] = i;
}
return false;
}
}
时间: 2024-12-09 16:33:59