Leetcode, leetcodeoj
Question:
Contains Duplicate 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] and nums [j] is at most t and the difference between I and j is at most k.
Analysis:
Use multiset to perform binary search of BST. Lower_bound () returns an iterator pointing to the first element greater than or equal to the input value.
Scans the array from left to right. If the number of elements in multiset is k + 1, delete the first element. Because multiset. size () is always less than or equal to k + 1, the subscript difference must be less than or equal to k. Then, use lower_bound () to find the first element that is greater than or equal to nums [I]-t. If the absolute value of the difference between this element and nums [I] is less than or equal to t, true is returned.
Note: To prevent overflow, data must be converted to long for processing!
class Solution {public: bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) { if(nums.size()<=1 || k<1 || t<0) return false; multiset<long long> mset; long long long_t=t; for(int i=0;i<nums.size();++i) { if(mset.size()==k+1) { auto it=mset.find(nums[i-k-1]); mset.erase(it); } long long tmp=nums[i]; auto it=mset.lower_bound(tmp-long_t); if(it!=mset.end()) { long long diff=*it>tmp?*it-tmp:tmp-*it; if(diff<=long_t) return true; } mset.emplace(nums[i]); } return false; }};