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

posted on 2017-04-25 09:28  Sempron2800+  阅读(103)  评论(0编辑  收藏  举报