Extension: For all combinations of i and j, the difference between i and j is at most k. Or only one exits


  • -1
    Z

    //For all combinations

    bool containsNearbyDuplicate(vector<int>& nums, int k) { 
            int size = nums.size();
            unordered_map<int,int> m;
            int count = 0;
            for(int i=0;i<size;i++)
            {
                if(m[nums[i]]==0)
                {
                    m[nums[i]] = i+1;
                }
                else
                {
                    count=1;
                    if(i-m[nums[i]]+1>k)
                        return false;
                }
            }
            if(count==1)
                return true;
            return false;
        }
    

    //Only one

    bool containsNearbyDuplicate(vector<int>& nums, int k) {
            int size = nums.size();
            unordered_map<int,int> m;
            int count = 0;
    
            for(int i=0;i<size;i++)
            {
                if(m[nums[i]]==0)
                {
                    m[nums[i]] = i+1;
                }
                else
                {
                    if(i-m[nums[i]]+1<=k)
                    {
                        count++;
                        if(count>1)
                             return false;
                    }
                    m[nums[i]] = i+1;
                }
            }
            if(count==1)
                return true;
            return false;
        }

Log in to reply
 

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