Saturday, July 9, 2016

Contains Duplicates III

Given an array of integers, find out whether there are two distinct indices i and j in the array such that the difference between nums[i] andnums[j] is at most t and the difference between i and j is at most k.

Solution:

class Solution {
public:
    static int comp(pair<int, int> p1, pair<int, int> p2) {
        return p1.first < p2.first;
    }
    // Sliding window of t and search for index differnces.
    bool findAlmostDup(vector<pair<int, int> > pairs, int k, int t) {
        int size = pairs.size(), beg = 0, end = 1;
        while (beg < size && end < size) {
            if (abs(long(pairs[end].first) - long(pairs[beg].first)) <= t) {
                int i = beg;
                while (i < end) {
                    if (abs(pairs[end].second - pairs[i].second) <= k) {
                        return true;
                    } else {
                        i++;
                    }
                }
                end++;
            } else {
                beg++;
                if (beg == end) {
                    end++;
                }
            }
        }
        return false;
    }
    bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
        int size = nums.size();
        if (size < 2)
            return false;
           
        //sort(nums.begin(), nums.end());
        vector<pair<int, int> > pairs;
        for (int i = 0; i < size; i++) {
            pairs.push_back(make_pair(nums[i], i));
        }
        sort(pairs.begin(), pairs.end(), comp);
        return findAlmostDup(pairs, k, t);
    }
};

No comments:

Post a Comment