Contains Duplicate III in C++



Suppose we have an array of integers, we have to check whether there are two distinct indices i and j in the array such that the absolute difference between nums[i] and nums[j] is at most t. And the absolute difference between i and j is at most k. So if input is like [1,2,3,1], then if k = 3 and t = 0, then return true.

To solve this, we will follow these steps −

  • Make a set s, n := size of nums array

  • for i in range 0 to n – 1

    • x is index of set element starting from nums[i] and above

    • if x is not in range of the set and value of x <= nums[i] + t, then return true

    • if x is not the first element

      • x := next element as random

      • if t th element starting from x is >= nums[i], then return true

    • insert nums[i] into s, then delete nums[i - k] from s

  • return false

Example(C++)

Let us see the following implementation to get a better understanding −

 Live Demo

#include <bits/stdc++.h> using namespace std; class Solution {    public:    bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {       multiset <int> s;       int n = nums.size();       for(int i = 0; i< n; i++){          multiset <int> :: iterator x = s.lower_bound(nums[i]);          if(x != s.end() && *x <= nums[i] + t ) return true;             if(x != s.begin()){                x = std::next(x, -1);                if(*x + t >= nums[i])return true;             }             s.insert(nums[i]);             if(i >= k){                s.erase(nums[i - k]);             }          }          return false;       } }; main(){    Solution ob;    vector<int> v = {1,2,3,1};    cout << (ob.containsNearbyAlmostDuplicate(v, 3,0)); }

Input

[1,2,3,1] 3 0

Output

1
Updated on: 2020-05-02T07:11:25+05:30

340 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements