LeetCode Contains Duplicate III
2015-06-07 11:31
429 查看
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.
要是面试,那么我已经跪了
用set不靠谱啊,这个提示binary search tree难道不是这么用,直接TLE了:
要是面试,那么我已经跪了
class Solution { public: bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) { if (t < 0 || k <1) { return false; } long bucket_size = (long)t + 1; long len = nums.size(); unordered_map<long, long> buckets; for (long i=0; i<len; i++) { long val = nums[i] - (long)INT_MIN; long bucket = val / bucket_size; // check duplicates in buckets[bucket-1], buckets[bucket], buckets[bucket+1] if (buckets.count(bucket) > 0 || buckets.count(bucket-1) > 0 && val - buckets[bucket - 1] <= t || buckets.count(bucket+1) > 0 && buckets[bucket + 1] - val <= t) { return true; } // maintain buckets entries in a k size window (the index constrains) if (buckets.size() >= k) { int bucket2del = (nums[i - k] - (long)INT_MIN) / bucket_size; buckets.erase(bucket2del); } buckets[bucket] = val; } return false; } };
用set不靠谱啊,这个提示binary search tree难道不是这么用,直接TLE了:
class Solution { public: bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) { if (t < 0 || k <1) { return false; } int len = nums.size(); set<long> win; for (int i=0; i<len; i++) { long val = nums[i]; auto lo = lower_bound(win.begin(), win.end(), val - t); if (lo != win.end()) { if (abs(*lo - val) <= t) { return true; } else { // not found } } // sliding window if (i >= k) { win.erase(nums[i - k]); } win.insert(val); } return false; } };
相关文章推荐
- 使用ssh框架时出现 failed to lazily initialize 或者 no session 异常
- 人工智能搜索算法(深度优先、迭代加深、一致代价、A*搜索)
- URAL 1457. Heating Main
- Contains Duplicate
- 如何在 Ubuntu 中更改默认浏览器和 Email 客户端
- ISP Pipeline的关键模块之Demosaic( 三)
- LeetCode Contains Duplicate II
- Aizu 0005
- 错误 1 error LNK2019: 无法解析的外部符号 "public: __thiscall chain<int>::~chain<int>(void)" (??1?$chain@H@@QAE@
- rails使用devise验证
- Microsoft.AlphaImageLoader过滤评论
- Contains Duplicate II
- linux使用mail命令发邮件―第三方smtp
- 我们iTailor智能衣橱项目想法v1.0
- 如何使用Openair4G的OTG以及进行ping操作
- [LeetCode] Contains Duplicate(II,III)
- grails瞬时属性
- VC2008中ActiveX Control Test Container程序去那里了?
- grails不能调试
- 五子棋AI算法浅谈