[LeetCode] Contains Duplicate III
2015-06-01 15:33
369 查看
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.一开始理解错题目了,还以为是要求所有的数对都必须符合要求,一直超时。其实题目是问是不是存在一个符合条件的数对,所以就容易多了,维护一个大小为 k 的二叉搜索树,来一个新的元素时,在BST上二分搜索有没有符合条件的数对,动态更新这个BST。因为BST的大小为 k 或不超过 k,所以这里面的数下标的差值一定是符合条件的。还有几点要注意的就是nums[i]与nums[j]的差值的是绝对值,所以要分别找lower_bound跟upper_bound,数据比较坑爹,为了防止溢出,容器用long long类型的。
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]); if (lb != bst.end() && abs(*lb - nums[i]) <= t) return true; auto ub = bst.upper_bound(nums[i]); if (ub != bst.begin() && abs(*(--ub) - nums[i]) <= t) return true; bst.insert(nums[i]); } return false; } };
不用比较两次,直接找nums[i] - t的lower_bound, 这个值就是与nums[i]差值最近的值。
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); if (lb != bst.end() && *lb - nums[i] <= t) return true; bst.insert(nums[i]); } return false; } };
相关文章推荐
- socket domain 样例
- org.hibernate.AssertionFailure: null id don't flus
- socketpair初识
- LeetCode Container With Most Water
- http://blog.csdn.net/liuhe688/article/details/6715983/
- YT02-简单数学课堂题-1004 Fibonacci Again -(5.31日-烟台大学ACM预备队解题报告)
- Error Domain=NSCocoaErrorDomain Code=3000 "未找到应用程序的“aps-environment”的权利字符串" UserInfo=0x1bad30 {NSLocalizedDescription=未找到应用程序的“aps-environment”的权利字符串}
- Installation error: INSTALL_FAILED_CONFLICTING_PROVIDER 解决方案
- HackerRank - "Detecting Valid Latitude and Longitude Pairs"
- http error 503. the service is unavailable. sharepoint
- Leetcode Problem.172—Factorial Trailing Zeroes
- AIX下的nmon的使用
- 在可以调用OLE之前,必须将当前线程设置为单线程单元(STA)模式,请确保您的Main函数带有STAThreadAttribute
- shrio 权限管理filterChainDefinitions过滤器配置
- httpd: Could not reliably determine the server's fully qualified domain name
- leetcode_Contains Duplicate II_easy
- EAI和ESB
- leetcode_Contains Duplicate_easy
- AEAI CRM客户关系管理V1.0.3版发版说明
- 【译】使用Rails 4.2+ 测试异步邮件系统