public class Solution { Dictionary<int, List<int>> dic = new Dictionary<int, List<int>>(); public bool ContainsNearbyDuplicate(int[] nums, int k) { for (int i = 0; i < nums.Length; i++) { var cur = nums[i]; if (!dic.ContainsKey(nums[i])) { var list = new List<int>(); list.Add(i); dic.Add(nums[i], list); } else { dic[nums[i]].Add(i); } } foreach (var d in dic) { var list = d.Value; for (int i = 0; i < list.Count - 1; i++) { if (list[i + 1] - list[i] <= k) { return true; } } } return false; } }
https://leetcode.com/problems/contains-duplicate-ii/#/description