[LeetCode] 219. Contains Duplicate II 解题思路

时间:2024-09-11 14:37:26

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 difference between i and j is at most k.

问题:给定一个数组和整数 k ,判断是否存在两个相等元素,并且两个相等元素的下标差在 k 以内?

问题问是否存在一个子数组满足某种条件,首先想到的是滑动窗口(sliding window)的模型。

将 [0, k] 视为一个窗口,将窗口向右滑动直到滑到最右端,期间判断窗口中是否存在相等元素。只要其中一个窗口存在相等元素,即原题目存在相等元素,否则,不存在。

判断一个数是否存在于一个集合中,可以用 hash_table ,即 c++ 中的 unordered_map。

本题目的思路使用的是长度固定的滑动窗口,其他同样可以理解为滑动窗口的还有:

Search Insert Position,每次长度减半的滑动窗口

Minimum Size Subarray Sum ,  求最大/最小连续子数组的滑动窗口。窗口长度无规律。

     bool containsNearbyDuplicate(vector<int>& nums, int k) {

         if(k == ){
return false;
} unordered_map<int, int> int_cnt; for(int i = ; i <= k && i < nums.size() ; i++){
if(int_cnt.count(nums[i]) == ){
int_cnt[nums[i]] = ;
}else{
return true;
}
} for (int i = ; (i + k) < nums.size(); i++){
int_cnt.erase(nums[i-]); if(int_cnt.count(nums[i+k]) == ){
int_cnt[nums[i+k]] = ;
}else{
return true;
}
} return false;
}