[LeetCode] Contains Duplicate III

简介: This problem gets much trickier than Contains Duplicate and Contains Duplicate II.  The basic idea is to maintain a window of k numbers.

This problem gets much trickier than Contains Duplicate and Contains Duplicate II. 

The basic idea is to maintain a window of k numbers. For each new number, if there exists a number in the window with difference not larger than k, then return true. When we check every number and have not returned true, return false. Remember that we need to update the windows (erase the earliest added element) after it has more than k elements.

The code is actually pretty short if we take advantage of the STL set template and its method lower_bound.

 1     bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
 2         set<long long> windows;
 3         for (int i = 0; i < nums.size(); i++) {
 4             auto pos = windows.lower_bound(nums[i] - t);
 5             if (pos != windows.end() && *pos <= (long long)nums[i] + t)
 6                 return true;
 7             windows.insert(nums[i]);
 8             if (i >= k) windows.erase(nums[i - k]);
 9         }
10         return false;
11     }
目录
相关文章
|
Go
leetcode-每日一题1408. 数组中的字符串匹配(暴力枚举)和Golang里关于Index方法和Contains方法区别
题目要求我们找到字符串数组中存在字符串是其他单词的子字符串,看到题目给我们的n的范围是[1,100],所以我们可以通过暴力枚举用两个for循环一层指子串一层指找存在这个子串的单词,找到则找下个一个子串
304 0
leetcode-每日一题1408. 数组中的字符串匹配(暴力枚举)和Golang里关于Index方法和Contains方法区别
|
算法 Python
LeetCode 217. 存在重复元素 Contains Duplicate
LeetCode 217. 存在重复元素 Contains Duplicate
LeetCode 219: 存在重复元素 II Contains Duplicate II
题目: ​ 给定一个整数数组和一个整数 k,判断数组中是否存在两个不同的索引 i 和 j,使得 nums [i] = nums [j],并且 i 和 j 的差的绝对值最大为 k。 ​ Given an array of integers and an integer k, find o...
761 0
LeetCode 217:存在重复元素 Contains Duplicate
题目: 给定一个整数数组,判断是否存在重复元素。 Given an array of integers, find if the array contains any duplicates. 如果任何值在数组中出现至少两次,函数返回 true。
9714 0
|
存储 索引
LeetCode 219 Contains Duplicate II(包含重复数字2)(*)
版权声明:转载请联系本人,感谢配合!本站地址:http://blog.csdn.net/nomasp https://blog.csdn.net/NoMasp/article/details/50593169 翻译 给定一个整型数组和一个整型数K, 找出是否存在两个不同的索引i和j,使得nums[i] = nums[j], 并且它们之间的距离最大为K。
1109 0
|
测试技术
LeetCode 217 Contains Duplicate(包含重复数字)(Vector、hash)
版权声明:转载请联系本人,感谢配合!本站地址:http://blog.csdn.net/nomasp https://blog.csdn.net/NoMasp/article/details/50504102 翻译 给定一个整型数字数组,找出这个数组是否包含任何重复内容。
1161 0
|
Unix Shell Linux
LeetCode刷题 Shell编程四则 | 194. 转置文件 192. 统计词频 193. 有效电话号码 195. 第十行
本文提供了几个Linux shell脚本编程问题的解决方案,包括转置文件内容、统计词频、验证有效电话号码和提取文件的第十行,每个问题都给出了至少一种实现方法。
407 6
LeetCode刷题 Shell编程四则 | 194. 转置文件 192. 统计词频 193. 有效电话号码 195. 第十行
|
搜索推荐 索引 Python
【Leetcode刷题Python】牛客. 数组中未出现的最小正整数
本文介绍了牛客网题目"数组中未出现的最小正整数"的解法,提供了一种满足O(n)时间复杂度和O(1)空间复杂度要求的原地排序算法,并给出了Python实现代码。
492 2