leetcode 220: Contains Duplicate III
2015-08-29 15:04
531 查看
Use set to find numbers with time complexity of O(n*logk). Learned this from http://www.cnblogs.com/easonliu/p/4544073.html.
bucket is empty. If not, return true. But if so, I also need to check the bucket idx-1 and bucket idx+1. If the numbers in that two buckets have differences with nums[i] less than or equal to t, return true. Then if all buckets contains more than k numbers,
I need to erase the left most number.
This is learned from discuss: https://leetcode.com/discuss/38206/ac-o-n-solution-in-java-using-buckets-with-explanation.
class Solution { public: bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) { set<int> window; int n=nums.size(); for(int i=0;i<n;i++) { if(window.size()>k) window.erase(window.find(nums[i-k-1])); set<int>::iterator it; it=window.lower_bound(nums[i]-t); if(it!=window.end()&&abs(*it-nums[i])<=t) return true; window.insert(nums[i]); } return false; } };Use unordered map to implement the bucket sort can reduce the time complexity to O(n). The index of one bucket is calculated by idx=(nums[i]-INT_MIN)/(t+1). The reason I divide t+1 is to avoid the error when t is 0. Then I find out whether that
bucket is empty. If not, return true. But if so, I also need to check the bucket idx-1 and bucket idx+1. If the numbers in that two buckets have differences with nums[i] less than or equal to t, return true. Then if all buckets contains more than k numbers,
I need to erase the left most number.
This is learned from discuss: https://leetcode.com/discuss/38206/ac-o-n-solution-in-java-using-buckets-with-explanation.
class Solution { public: bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) { if(k<1||t<0) return false; unordered_map<long long,long long> bucket; int n=nums.size(); for(int i=0;i<n;i++) { long long idx=((long long)nums[i]-INT_MIN)/((long long)t+1); if(bucket.find(idx)!=bucket.end()|| bucket.find(idx-1)!=bucket.end()&&(long long)nums[i]-bucket[idx-1]<=(long long)t|| bucket.find(idx+1)!=bucket.end()&&bucket[idx+1]-(long long)nums[i]<=(long long)t) return true; bucket.insert(make_pair(idx,nums[i])); if(bucket.size()>k) { idx=((long long)nums[i-k]-INT_MIN)/((long long)t+1); bucket.erase(bucket.find(idx)); } } return false; } };
相关文章推荐
- 关于 I/O Wait
- STL源码剖析 [容器](四)[stl_pair.h]
- 电商网店平台| Haidao海盗电商开源网店系统 v1.9.0.150619 beta
- Aircrack-ng之Airmon-ng命令
- 错误: INSTALL_FAILED_VERSION_DOWNGRADE
- Rails Gem notification_exception
- BIO, NIO, AIO(转)
- PaintView 绘图控件解析
- SNOY VAIO 索尼电脑亮度自动变暗
- 啥是landscape,啥是portrait
- public static void main(String arg[]) 详细解释
- Leetcode: Contains Duplicate II
- 服务器维护手记-crontab引起大量sendmail进程打死内存问题
- Codeforces Round #317 [AimFund Thanks-Round] (Div. 2)
- Gmail打不开登录不了邮箱最新解决方法!
- leetcode 219: Contains Duplicate II
- Gym 100338H High Speed Trains(高精度)
- Reflow & Repaint
- Codeforces Round #317 [AimFund Thanks-Round] (Div. 1) C. CNF 2 无向图找环
- wait、sleep、notify、notifyAll的区别