leetcode - Contains Duplicate III

来源:互联网 发布:网络安全检查总结报告 编辑:程序博客网 时间:2024/05/12 08:42

题目:

Contains Duplicate III

 

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.


分析:

    利用multiset进行BST的二分搜索。lower_bound()返回一个迭代器,指向大于等于输入值的第一个元素。

    从左到右扫描数组,若multiset的元素数量等于k+1,则删去最先进入的元素。由于multiset.size()始终小于等于k+1,所以下标之差是肯定小于等于k的。然后利用lower_bound(),找到第一个大于等于nums[i]-t的元素,若该元素和nums[i]的差的绝对值小于等于t,则返回真。

  注意:为了防止溢出,必须将数据转化为long long进行处理!

class Solution {public:    bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {        if(nums.size()<=1 || k<1 || t<0)            return false;                    multiset<long long> mset;        long long long_t=t;                for(int i=0;i<nums.size();++i)        {            if(mset.size()==k+1)            {                auto it=mset.find(nums[i-k-1]);                mset.erase(it);            }            long long tmp=nums[i];            auto it=mset.lower_bound(tmp-long_t);            if(it!=mset.end())            {                long long diff=*it>tmp?*it-tmp:tmp-*it;                if(diff<=long_t)                    return true;            }            mset.emplace(nums[i]);        }        return false;    }};






0 0