Contains Duplicate III 重复数 堆实现

来源:互联网 发布:淘宝特卖入口 编辑:程序博客网 时间:2024/05/24 02:26

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.

class Solution {public://因为堆的性质 iterator lower_bound (const value_type& val) const可以用于返回值小于等于val的元素的迭代器    bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {                if(nums.size()<2||k<1||t<0)            return false;        multiset<int> has;        int len=nums.size();                for(int i=0;i<len-1;)        {            has.insert(nums[i]);            i++;            multiset<int>::iterator it=has.lower_bound(nums[i]-t);            if(it!=has.end() && (*it-nums[i] >=-t && *it-nums[i]<=t) )                return true;            if(i>=k)                has.erase(nums[i-k]);        }        return false;    }};

0 0
原创粉丝点击