Simple solution in C# using Dictionary


  • 0
    K
    public class Solution {
        public bool ContainsNearbyDuplicate(int[] nums, int k) {
            
            Dictionary<int,int> map = new Dictionary<int,int>();
            
            for(int i=0; i<nums.Length; i++)
            {
                if(map.ContainsKey(nums[i]))
                {
                    if(i - map[nums[i]] <=  k)
                        return true;
                    else
                        map[nums[i]]=i;
                }
                else
                {
                    map.Add(nums[i], i);
                }
            }
            return false;
        }
    }
    
    

Log in to reply
 

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