219. Contains Duplicate II
給定一個整數數組 nums 和一個整數 k,如果數組中存在兩個不同的索引 i 和 j,使得 nums[i] == nums[j] 且 abs(i - j) <= k,則返回 true。
範例:
輸入:nums = [1, 2, 3, 1], k = 3 輸出:true
Python
class Solution:
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
index_map = {}
for i, num in enumerate(nums):
if num in index_map and i - index_map[num] <= k:
return True
index_map[num] = i
return False
29.97MB, 457ms
C++
#include <vector>
#include <unordered_map>
using namespace std;
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
unordered_map<int, int> index_map;
for (int i = 0; i < nums.size(); ++i) {
if (index_map.find(nums[i]) != index_map.end() && i - index_map[nums[i]] <= k) {
return true;
}
index_map[nums[i]] = i;
}
return false;
}
};
81.23MB, 116ms
Javascript
/**
* @param {number[]} nums
* @param {number} k
* @return {boolean}
*/
var containsNearbyDuplicate = function(nums, k) {
const indexMap = new Map();
for (let i = 0; i < nums.length; i++) {
if (indexMap.has(nums[i]) && i - indexMap.get(nums[i]) <= k) {
return true;
}
indexMap.set(nums[i], i);
}
return false;
};
73.49MB, 95ms