算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !
今天和大家聊的问题叫做 存在重复元素 III,我们先来看题面:
https://leetcode-cn.com/problems/contains-duplicate-iii/
Given an integer array nums and two integers k and t, return true if there are two distinct indices i and j in the array such that abs(nums[i] - nums[j]) <= t and abs(i - j) <= k.
在整数数组 nums 中,是否存在两个下标 i 和 j,使得 nums [i] 和 nums [j] 的差的绝对值小于等于 t ,且满足 i 和 j 的差的绝对值也小于等于 ķ 。
如果存在则返回 true,不存在返回 false。
示例
示例 1:
输入: nums = [1,2,3,1], k = 3, t = 0
输出: true
示例 2:
输入: nums = [1,0,1,1], k = 1, t = 2
输出: true
示例 3:
输入: nums = [1,5,9,1,5,9], k = 2, t = 3
输出: false
解题
注意:整数溢出的情况
利用set的lower_bound函数返回>= key的元素,不存在时返回end()
it = s.lower_bound(nums[i] - long(t));
if(it != s.end() && (*it - nums[i]) <= t) {
return true;
}
i和j之间差的绝对值最大为k的元素保存到set容器中去
if(s.size() > k) {
s.erase(nums[i - k]);
}
class Solution {
public:
bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
set<long> s;
for(int i = 0; i < nums.size(); i++) {
auto it = s.lower_bound(nums[i] - long(t));
if(it != s.end() && *it - nums[i] <= t) {
return true;
}
s.insert(nums[i]);
if(s.size() > k) {
s.erase(nums[i - k]);
}
}
return false;
}
};
好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。
上期推文: