给定一个整数数组和一个整数 k,判断数组中是否存在两个不同的索引 i 和 j,使得 nums [i] = nums [j],并且 i 和 j 的差的绝对值最大为 k。
示例 1:
输入: nums = [1,2,3,1], k = 3
输出: true
示例 2:
输入: nums = [1,0,1,1], k = 1
输出: true
示例 3:
输入: nums = [1,2,3,1,2,3], k = 2
输出: false
方法一:暴力搜索法。直接穷举下标。(时间复杂度O(k * n), 额外空间复杂度O(1))
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
int numsSize = nums.size();
//判断nums[i]是否重复
for (int beginIndex = 0; beginIndex < numsSize; ++beginIndex){
//搜索范围[beginIndex + 1, begnIndex + k]
for (int endIndex = beginIndex + 1; endIndex < numsSize && endIndex - beginIndex <= k; ++endIndex){
if (nums[beginIndex] == nums[endIndex]){
return true;
}
}
}
return false;
}
};
方法二:请先翻阅 LeetCode 存在重复元素
这题仍然使用map容器,但是是将值与最近出现的下标关联。(时间复杂度O(n), 额外空间复杂度O(n))
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
int numsSize = nums.size();
map<int, int> myMap;//用于将元素的值与最近出现的下标关联
//扫描数组
for (int beginIndex = 0; beginIndex < numsSize; ++beginIndex){
if (myMap.count(nums[beginIndex]) != 0 && beginIndex - myMap[nums[beginIndex]] <= k){//如果这个元素之前出现过、下标是否合格
return true;
}
myMap[nums[beginIndex]] = beginIndex;//否则更新为最近出现的下标
}
return false;
}
};