leetcode,leetcodeoj
題目:
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.
分析:
利用multiset進行BST的二分搜尋。lower_bound()返回一個迭代器,指向大於等於輸入值的第一個元素。
從左至右掃描數組,若multiset的元素數量等於k+1,則刪去最先進入的元素。由於multiset.size()始終小於等於k+1,所以下標之差是肯定小於等於k的。然後利用lower_bound(),找到第一個大於等於nums[i]-t的元素,若該元素和nums[i]的差的絕對值小於等於t,則返回真。
注意:為了防止溢出,必須將資料轉化為long long進行處理!
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; }};