C# accepted, O(n), using HashSet.


  • 0
    R

    The basic idea here is to maintain a HashSet size = k, if any new element coming in that is duplicated, return true.

    public bool ContainsNearbyDuplicate(int[] nums, int k) {
                
            bool result = false; 
            if (k == 0)
            {
                return result;
            }
       
            HashSet<int> hash = new HashSet<int>();
            for (int i = 0; i < nums.Length; i++)
            {
                if (hash.Contains(nums[i]))
                {
                    result = true;
                    break;
                }
                else
                {
                    if (hash.Count == k)
                    {
                        hash.Remove(nums[i - k]);
                    }
                    hash.Add(nums[i]);
                }
            }
            return result;
        }

Log in to reply
 

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