A 5-Line C# Solution


  • 0
    L
    public bool ContainsNearbyDuplicate(int[] nums, int k) {
        Dictionary<int, int> hist = new Dictionary<int, int>();
        for(int i = 0; i < nums.Length; i++)
            if(hist.ContainsKey(nums[i]) && i - hist[nums[i]] <= k) return true;
            else hist[nums[i]] = i;
        return false;
    }
    
    
    public bool ContainsNearbyDuplicate(int[] nums, int k) {
        ISet<int> set = new HashSet<int>();
        for(int i = 0; i < nums.Length; i++){
            if(set.Contains(nums[i])) return true;
            set.Add(nums[i]);
            if(i >= k) set.Remove(nums[i - k]);
        }
        return false;
    }

Log in to reply
 

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