LeetCode-219. Contains Duplicate II

网友投稿 282 2022-08-29

LeetCode-219. Contains Duplicate II

Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k.

Example 1:

Input: nums = [1,2,3,1], k = 3Output: true

Example 2:

Input: nums = [1,0,1,1], k = 1Output: true

Example 3:

Input: nums = [1,2,3,1,2,3], k = 2Output: false

题解:

同样使用set存储前k - 1个值。

class Solution {public: bool containsNearbyDuplicate(vector& nums, int k) { unordered_set s; int n = nums.size(); if (k <= 0) { return false; } if (k > n) { k = n - 1; } for (int i = 0; i < n; i++) { if (i > k) { s.erase(nums[i - k - 1]); } if (s.find(nums[i]) != s.end()) { return true; } s.insert(nums[i]); } return false; }};

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:LeetCode-209. Minimum Size Subarray Sum
下一篇:YYDS、AWSL、DDDD……网络热梗的好感度周期为什么越来越短?
相关文章

 发表评论

暂时没有评论,来抢沙发吧~