leetcode.220. Contains Duplicate III
2016-05-10 23:12
651 查看
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.
问题描述:判断数组中是否存在<ai aj> abs(ai - aj)<=t && abs(i - j) <=k;
问题分析:需要一个数据结构来维护满足条件k。单纯暴力,会超时。假设当前元素num[i]我只需要判断 i- k -1 到 i之间的元素的关系就可以了。假设当前元素是num[i], 另一个元素a(multiset中的),他们满足| a - num[i]|<=t 可得到 num[i] - t <= a <= num[i] + t。所以我需要尽快找到 num[i] - t 的下界(lb)(第一个大于等于 num[i] - t的值)然后在判断 |lb - num[i]| <= t是否满足 。
问题解决:这里使用multiset来维护最多k个元素。区别与set , multiset可以存储多个相同的元素。然后按照升序关系排列。
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.
问题描述:判断数组中是否存在<ai aj> abs(ai - aj)<=t && abs(i - j) <=k;
问题分析:需要一个数据结构来维护满足条件k。单纯暴力,会超时。假设当前元素num[i]我只需要判断 i- k -1 到 i之间的元素的关系就可以了。假设当前元素是num[i], 另一个元素a(multiset中的),他们满足| a - num[i]|<=t 可得到 num[i] - t <= a <= num[i] + t。所以我需要尽快找到 num[i] - t 的下界(lb)(第一个大于等于 num[i] - t的值)然后在判断 |lb - num[i]| <= t是否满足 。
问题解决:这里使用multiset来维护最多k个元素。区别与set , multiset可以存储多个相同的元素。然后按照升序关系排列。
class Solution { public: bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) { multiset<long long> bst; for (int i = 0; i < nums.size(); ++i) { if (bst.size() == k + 1) bst.erase(bst.find(nums[i - k - 1])); auto lb = bst.lower_bound(nums[i] - t);//第一个大于等num[i]的元素位置 if (lb != bst.end() && *lb - nums[i] <= t) return true; bst.insert(nums[i]); } return false; } };
相关文章推荐
- poj-1273 Drainage Ditches(最大流基础题)
- Ext.Panel 面板控件、 Ext.window.Window 窗口控件、 Ext.container.Viewport 布局控件
- APS.NET_MVC5学习笔记- 查询Details和Delete方法
- leetcode 182. Duplicate Emails
- 图像特效---Oilpaint油画滤镜
- 再以Circle类为直接基类,派生出一个Cylinder(圆柱体)类,再增加数据成员h(高),,以及求圆柱表面积的成员函数area和求圆柱体积的成员函数volume,实现需要的成员函数,并设计main
- TensorFlow人工智能入门教程之十三 RCNN 区域卷积网络(视频侦测分析人脸侦测区域检测 )
- http://www.cnblogs.com/kristain/articles/2033566.html
- int main(int argc,char* argv[]),int main(int argc,char** argv)
- HDU 4393 Throw nails
- maridb Error 'Operation DROP USER failed for
- AIDL(跨进程通信传输语言)的用法
- LeetCode-11. Container With Most Water
- HDOJ 1021 Fibonacci Again
- 关于AIDL客户端与服务端交互的包名问题-package
- Kafka设计解析(三)- Kafka High Availability (下)
- Kafka设计解析(二)- Kafka High Availability (上)
- Rails中如何避免N+1问题
- Ex2010-03 figure out the number of mailboxes per database
- leetcode 336. Palindrome Pairs