Given an integer array nums
and an integer k
, return true
if there are two distinct indices i
and j
in the array such that nums[i] == nums[j]
and abs(i - j) <= k
.
Example 1:
Input: nums = [1,2,3,1], k = 3 Output: true
Example 2:
Input: nums = [1,0,1,1], k = 1 Output: true
Example 3:
Input: nums = [1,2,3,1,2,3], k = 2 Output: false
Constraints:
1 <= nums.length <= 105
-109 <= nums[i] <= 109
0 <= k <= 105
Solution: Sliding Window + Hashtable
Hashtable to store the last index of a number.
Remove the number if it’s k steps behind the current position.
Time complexity: O(n)
Space complexity: O(n)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
// Author: Huahua class Solution { public: bool containsNearbyDuplicate(vector<int>& nums, int k) { unordered_map<int, int> m; // num -> last index for (int i = 0; i < nums.size(); ++i) { if (i > k && m[nums[i - k - 1]] < i - k + 1) m.erase(nums[i - k - 1]); if (m.count(nums[i])) return true; m[nums[i]] = i; } return false; } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment