LeetCode OJ:Contains Duplicate III(是否包含重复)
2015-10-17 16:05
218 查看
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的两个数的值小于t就可以满足要求,返回true。 这里使用multiset来实现,因为其底层使用的是红黑数,一斤排好序了,而且查找性能好,不会出现out of time的情况,主要的想法是遍历vector,当multiset的大小小于k的时候插入,判断当前值在整个set中是否有值与其相差t及以下,由于存在lower_bound,还是比较方便的。
感觉以前写的c++的版本写的比较怪,下面是java写的,其实维持一个长度为k的窗口不一定需要用multiSet直接使用java中的treeSet接可以维持一个,lower_bound以及upper_bound函数实际上也是不需要的,代码如下所示:
这个类似前面两篇博客,只不过这里距离小于k的两个数的值小于t就可以满足要求,返回true。 这里使用multiset来实现,因为其底层使用的是红黑数,一斤排好序了,而且查找性能好,不会出现out of time的情况,主要的想法是遍历vector,当multiset的大小小于k的时候插入,判断当前值在整个set中是否有值与其相差t及以下,由于存在lower_bound,还是比较方便的。
class Solution { public: bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) { multiset<long long> ret; int sz = nums.size(); for (int i = 0; i < sz; ++i){ if (ret.size() == k + 1) ret.erase(ret.find(nums[i - k -1])); auto lb = ret.lower_bound(nums[i] - t); // 这个表达式规定了*lb - nums[i] > -t if (lb != ret.end() && *lb - nums[i] <= t)return true; //这个规定了*lb - num[i] < t; ret.insert(nums[i]); } return false; } };
感觉以前写的c++的版本写的比较怪,下面是java写的,其实维持一个长度为k的窗口不一定需要用multiSet直接使用java中的treeSet接可以维持一个,lower_bound以及upper_bound函数实际上也是不需要的,代码如下所示:
public class Solution { public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) { if(k < 1|| t < 0 || nums == null || nums.length < 2) return false; SortedSet<Long> set = new TreeSet<Long>(); for(int i = 0; i < nums.length; ++i){ SortedSet<Long> subSet = set.subSet((long)nums[i] - t, (long)nums[i] + t + 1); if(!subSet.isEmpty()) return true; if(i >= k){//维持一个长度为k的窗口,就是说窗口一只向前滑动 set.remove((long)nums[i-k]); } set.add((long)nums[i]); } return false; } }
相关文章推荐
- available()在不同的地方使用,结果不同
- 异常安全,RAII与C++11 http://www.cnblogs.com/mavaL/articles/2515381.html
- 【C++设计技巧】C++中的RAII机制 http://www.cnblogs.com/gnuhpc/archive/2012/12/04/2802307.html
- LeetCode OJ:Contains DuplicateII(是否包含重复II)
- LeetCode OJ:Contains Duplicate(是否包含重复)
- Code Forces 585 B. Phillip and Trains(BFS)
- 构造函数中抛出的异常 http://blog.csdn.net/deyili/article/details/6332760
- No Entertainment!
- apk安装故障INSTALL_FAILED_INSUFFICIENT_STORAGE
- hdoj 2389 Rain on your Parade 【HK】
- vim 集成环境搭建之vim-main
- Mybatis错误:Parameter 'XXX' not found. Available parameters are [1, 0, param1, param2]
- Mybatis错误:Parameter 'XXX' not found. Available parameters are [1, 0, param1, param2]
- C++中的RAII机制 http://www.jellythink.com/archives/101
- AIDL(1)
- RAII惯用法:C++资源管理的利器 http://www.cnblogs.com/hsinwang/articles/214663.html
- CF Round #325 Div2 D. Phillip and Trains
- LeetCode -- Climbing Stairs
- 配置RAID
- golang辟谣之RAII