码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode OJ:Contains Duplicate III(是否包含重复)

时间:2015-10-17 17:39:40      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:

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,还是比较方便的。

 1 class Solution {
 2 public:
 3     bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
 4         multiset<long long> ret;
 5         int sz = nums.size();
 6         for (int i = 0; i < sz; ++i){
 7             if (ret.size() == k + 1)
 8                 ret.erase(ret.find(nums[i - k -1]));
 9             auto lb = ret.lower_bound(nums[i] - t); //  这个表达式规定了*lb - nums[i] > -t
10             if (lb != ret.end() && *lb - nums[i] <= t)return true;  //这个规定了*lb - num[i] < t;
11             ret.insert(nums[i]);
12         }
13         return false;
14     }
15 };

 

LeetCode OJ:Contains Duplicate III(是否包含重复)

标签:

原文地址:http://www.cnblogs.com/-wang-cheng/p/4887646.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!