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

LeetCode:Contains Duplicate Ⅲ

时间:2015-06-08 16:35:07      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:

problems:

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的加入multiset中,同时要查看是否有符合条件t的  时间复杂度o(n)

class Solution {
public:
    bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
       
       multiset<int> set;
       for(int i=0;i<nums.size();i++)
       {
       if(set.size()==k+1)
       {
           set.erase(set.find(nums[i-k-1]));   
       }
       
       auto it=set.lower_bound(nums[i]-t);     //这儿不能用abs(nums[i]) 涉及到负数case 无法通过 [-1 -1] 2 0
      
       if(it!=set.end())
       {
            int gap = abs(nums[i]-*it);
            if(gap<=t)
               return true;
       }       
       set.insert(nums[i]);
       }
       return false;
        
    }
};

 

LeetCode:Contains Duplicate Ⅲ

标签:

原文地址:http://www.cnblogs.com/xiaoying1245970347/p/4561029.html

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