[刷题] 220 Contains Duplicate III
要求
- 给出整型数组nums和整数k,是否存在索引i和j
- 使得nums[i]和nums[j]之差不超过t,且i和j之差不超过k
思路
- 建立k个元素的有序查找表
- 每次有新元素加入,寻找查找表中大于 nums[i]-t 的最小值,若存在且此值小于 nums[i]+t,则目标元素存在
- set底层是二叉树实现,时间(nlogn),空间(k)
- vector中的int值相加可能产生整型溢出,set中使用64位整数 long long
实现
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 class Solution { 2 public: 3 bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) { 4 if(t < 0) 5 return false; 6 7 set<long long> record; 8 for(int i = 0 ; i < nums.size() ; i ++){ 9 10 if(record.lower_bound((long long)nums[i] - (long long)t) != record.end() && 11 *record.lower_bound((long long)nums[i] - (long long)t ) <= (long long)nums[i] + (long long)t) 12 return true; 13 14 record.insert(nums[i]); 15 16 if(record.size() == k + 1) 17 record.erase( nums[i-k] ); 18 } 19 20 return false; 21 } 22 };