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的划窗,那么问题就在于用什么数据结构来构造这个划窗。因为当新的数字进来后,咱们须要比较它和划窗内其余数字的大小关系,从搜索的效率角度出发,能够使用BST,所以咱们选择STL中的SET容器来构造这个划窗。函数
思路也很简单,当新进来一个数后,先在容器中寻找是否有比nums[i]-t大的数字,这一步能够利用lower_bound函数实现,以后再比较比nums[i]-t大的数字中最小的那个与nums[i]的差,若是符合条件就返回true。post
另外不要忘记划窗移动时,删除和插入相应的元素。spa
class Solution { public: bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) { if (k < 0) { return false; } set<int> window; for (int i = 0; i < nums.size(); ++i) { if (i > k) { window.erase(nums[i-k-1]); } auto pos = window.lower_bound(nums[i] - t); if (pos != window.end() && *pos - nums[i] <= t) { return true; } window.insert(nums[i]); } return false; } };