219. Contains Duplicate II

xiaoxiao2021-02-27  466

原题

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; }
转载请注明原文地址: https://www.6miu.com/read-2606.html

最新回复(0)