LeetCode 220 Contains Duplicate III

来源:互联网 发布:怎样应聘淘宝模特 编辑:程序博客网 时间:2024/05/22 06:34


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] andnums[j] is at most t and the difference between i andj is at most k.

题目要求:数组nums中,是否存在i, j,满足abs(nums[i]-nums[j]) <= t, abs(i-j) <= k。


使用了set对问题进行求解。


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


在完成了III之后,又把I和II做了。有了III的基础,I和II很容易就解决了。



0 0
原创粉丝点击