/** * @param{number[]} nums * @param{number} k * @return{boolean} */varcontainsNearbyDuplicate=function (nums, k) {constvisited= {};for (let i =0; i <nums.length; i++) {constnum= nums[i];if (visited[num] !==undefined&& i - visited[num] <= k) {returntrue; } visited[num] = i; }returnfalse;};
Python Code:
classSolution:defcontainsNearbyDuplicate(self,nums: List[int],k:int) ->bool: d ={}for index, num inenumerate(nums):if num in d and index - d[num]<= k:returnTrue d[num]= indexreturnFalse
C++ Code:
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
auto m = unordered_map<int, int>();
for (int i = 0; i < nums.size(); ++i) {
auto iter = m.find(nums[i]);
if (iter != m.end()) {
if (i - m[nums[i]] <= k) {
return true;
}
}
m[nums[i]] = i;
}
return false;
}
};