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

本文介绍了一个算法问题:如何判断一个整数数组中是否存在两个不同的索引 i 和 j,使得 nums[i] = nums[j] 并且 i 和 j 的绝对差不超过 k。通过使用字典来跟踪已遍历元素及其索引,可以有效地解决这个问题。
668

被折叠的 条评论
为什么被折叠?



