[leetcode] Contains Duplicate III
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.
分析:这道题有两个限制条件,两个数字的坐标差不能大于k,值差不能大于t。我们使用multiset数据结构来解决,维护一个k大小的窗口,这样保证两个数字之间的坐标差不大于k,然后使用multiset数据结构的lower_bound()函数来找一个特定的范围,就是大于或者等于nums[i]-t的位置,然后看这个位置之后的数字是否满足与nums[i]的差的绝对值小于等于t,如果存在一个满足的情况,则返回true。最后遍历完整个数组返回false。
1 class Solution 2 { 3 public: 4 bool containsNearbyAlmostDuplicate(vector<int> &nums, int k, int t) 5 { 6 multiset<int> S; 7 int start = 0, end = 0; 8 for(int i=0; i<nums.size(); i++) 9 { 10 if(S.size() == k+1) S.erase(nums[i-k-1]); 11 auto it = S.lower_bound(nums[i]-t); 12 if(it != S.end() && abs(*it - nums[i]) <= t) return true; 13 S.insert(nums[i]); 14 } 15 16 return false; 17 } 18 };