leetcode.220. Contains Duplicate III

来源:互联网 发布:slack mac 版 编辑:程序博客网 时间:2024/04/29 08:25

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.

问题描述:判断数组中是否存在<ai aj> abs(ai - aj)<=t  && abs(i - j) <=k;

问题分析:需要一个数据结构来维护满足条件k。单纯暴力,会超时。假设当前元素num[i]我只需要判断 i- k -1 到 i之间的元素的关系就可以了。假设当前元素是num[i], 另一个元素a(multiset中的),他们满足| a - num[i]|<=t     可得到   num[i] - t  <= a <=  num[i] + t。所以我需要尽快找到 num[i] - t 的下界(lb)(第一个大于等于 num[i] - t的值)然后在判断 |lb - num[i]| <= t是否满足 。

问题解决:这里使用multiset来维护最多k个元素。区别与set , multiset可以存储多个相同的元素。然后按照升序关系排列。

class Solution {public:    bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {         multiset<long long> bst;          for (int i = 0; i < nums.size(); ++i) {              if (bst.size() == k + 1) bst.erase(bst.find(nums[i - k - 1]));              auto lb = bst.lower_bound(nums[i] - t);//第一个大于等num[i]的元素位置              if (lb != bst.end() && *lb - nums[i] <= t) return true;              bst.insert(nums[i]);         }         return false;    }};



0 0
原创粉丝点击