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

220. Contains Duplicate III

时间:2016-03-16 01:41:35      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:contains duplicate

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.


解法:

这里的 t,k 均是大于0的,

用 set 保存当前位置前边的k个位置的数据,A: nums[i]

set 中的某个数据可用x表示。这里选用set的原因是 下边会用到求下界操作

则当满足下式时返回true

|x-A|<=t

-t<=x-A<=t

观察左半边:-t<=x-A,则满足条件的x>=A-t,即需要查找set中是否有大于或者等于(A-t)的数,如果有,则进行下一步判断。否则继续往后扫描数组。

如果set中有这样A-t的下界存在,假定这个数为X,

则满足:X-A<=t 时返回true

bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
        int size=nums.size();
        if(size<=1||k<=0)
            return false;
        
        set<int> table;
        for(int i=0;i<size;++i){
            if(i>k){
                table.erase(nums[i-k-1]);
            }
            auto it=table.lower_bound(nums[i]-t);
            if(it!=table.end()&&*it-nums[i]<=t)
                return true;
            table.insert(nums[i]);
        }
        return false;
    }


220. Contains Duplicate III

标签:contains duplicate

原文地址:http://searchcoding.blog.51cto.com/1335412/1751400

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