首页 > 其他 > 详细

220. Contains Duplicate III

时间:2016-03-16 01:39:27      阅读:264      评论: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.


解法:

这里的 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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!