题目描述:
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.
给定一个数组,遍历每个数,找出是否存在nums[i]和nums[j]相等并且i和j的距离小于等于k。
思路:
本题考查的还是哈希表的使用,直接用哈希表存每个数字的所有位置。
实现代码:
public class Solution {
public bool ContainsNearbyDuplicate(int[] nums, int k) {
if(nums == null || nums.Length == 0){
return false;
}
var dict = new Dictionary<int ,IList<int>>();
for (var i = 0;i < nums.Length; i++){
if(!dict.ContainsKey(nums[i])){
dict.Add(nums[i], new List<int>(){i});
}
else{
if(dict[nums[i]].Any(x=>(i-x) <= k)){
return true;
}else{
dict[nums[i]].Add(i);
}
}
}
return false;
}
}