219. Contains Duplicate II

来源:互联网 发布:unity3d跑酷游戏教程 编辑:程序博客网 时间:2024/06/16 20:36

原题

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;        }
2 0