LeetCode-Contains Duplicate III
2015-10-11 11:39
435 查看
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.
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.
class Solution { public: bool containsNearbyAlmostDuplicate(vector<int>&nums, int k, int t) { multiset<long long>bst;//set,multiset,map,multimap都是按照严格弱序保存的,所以插入一个元素不是简单的在末尾插入,它的插入有点类似二叉树。 for (int i = 0; i < nums.size(); ++i) { if (bst.size() == k + 1) bst.erase(bst.find(nums[i - k - 1]));//如果执行到这里还没有找到符合条件的值,那么前面nums[0]-nums[i-k-1]都没 //有存在的必要了。所以按照顺序,进一个删一个。nums[i-k-1]保证每次删除的 //都是前k个元素的头元素。 auto lb = bst.lower_bound(nums[i]); if (lb != bst.end() &&(abs(*lb - nums[i])<=t)) return true;//找到第一个大于等于它的数,后面就比它更大,所以nums[i]与bst后面的值无需比 //较。 auto ub = bst.upper_bound(nums[i]); if (ub != bst.begin() && abs(*(--ub) - nums[i]) <= t) return true;//考虑比它小的数的情况。 bst.insert(nums[i]); } return false; } };
相关文章推荐
- RAID
- 【人工智能】八皇后问题-启发式求解
- Container With Most Water
- Rails读书笔记第二章
- Rails读书笔记第一章
- NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9802)
- LeetCode-Contains Duplicate III
- use `free` to check available memory
- LeetCode-Contains Duplicate II
- LeetCode-Contains Duplicate 217
- http://blog.csdn.net/liulina603/article/details/8617281
- Codeforces Round #323 (Div. 2) D.Once Again...(582B)
- tools:context=".MainActivity的作用
- LeetCode-Contains Duplicate II
- LightOJ 1138 Trailing Zeroes (III)
- WinMain与WndProc以及窗口诞生过程总结
- CClientDC和CPaintDC、CWindowsDC之间的联系和区别
- *SocketException: recvfrom failed: ECONNRESET (Connection reset by peer)
- 17.1.1.4 Obtaining the Replication Master Binary Log Coordinate
- HDU 4810 Wall Painting