Leetcode 220 Contains Duplicate III Solution in c++ | Hindi Coding Community

0

 


You are given an integer array nums and two integers indexDiff and valueDiff.

Find a pair of indices (i, j) such that:

i != j,

abs(i - j) <= indexDiff.

abs(nums[i] - nums[j]) <= valueDiff, and

Return true if such pair exists or false otherwise.

 

Example 1:


Input: nums = [1,2,3,1], indexDiff = 3, valueDiff = 0

Output: true



class Solution {
public:
    bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t)
    {
        int n = nums.size();
        multiset<int> ms;    
       
        int i=0, j=0;
        while(j<n)
        {
            auto up = ms.upper_bound(nums[j]);
            if((up != ms.end() and *up-nums[j] <= t) || (up != ms.begin() and nums[j] - *(--up) <= t))
                return true;
            ms.insert(nums[j]);
           
            if(ms.size() == k+1)
            {
                ms.erase(nums[i]);
                i++;
            }
            j++;
        }
        return false;
    }
};


Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !