C# 164ms accepted solution


  • 1
    X
    public class Solution {
    public bool ContainsNearbyDuplicate(int[] nums, int k) {
        if (nums == null || k <= 0)
            return false;
        var hash = new Dictionary<int, List<int>>();
        for (int i = 0; i < nums.Length; ++i)
        {
            if (!hash.ContainsKey(nums[i]))
                hash.Add(nums[i], new List<int>());
            hash[nums[i]].Add(i);
        }
        foreach(var pair in hash)
        {
            if (pair.Value.Count > 1)
            {
                for(int j = 0; j < pair.Value.Count - 1; ++j)
                {
                    if (pair.Value[j + 1] - pair.Value[j] <= k)
                        return true;
                }
            }
        }
        return false;
    }
    

    }


  • 0
    A

    why not use hashset instead hashmap


  • 0
    A

    public class Solution {

    public bool ContainsNearbyDuplicate(int[] nums, int k) 
    

    {
    int N = nums.Length;
    HashSet<int> kSet = new HashSet<int>();

        for(int i=0;i<=k && i<N; i++ )
        {
            if(kSet.Contains(nums[i]))
                return true;
            kSet.Add(nums[i]);    
        }
        
        for(int i = k+1; i <N; i++)
        {
            kSet.Remove(nums[i-k-1]);
            if(kSet.Contains(nums[i]))
                return true;
            else 
                kSet.Add(nums[i]);
        }
        
        return false;
        
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.