Contains Duplicate II
Given an array of integers and an integer k, return true if and only if 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.
https://leetcode.com/problems/contains-duplicate-ii/
1 /** 2 * @param {number[]} nums 3 * @param {number} k 4 * @return {boolean} 5 */ 6 var containsNearbyDuplicate = function(nums, k) { 7 var map = {}; 8 for(var i in nums){ 9 if(map[nums[i]] !== undefined){ 10 if(Math.abs(map[nums[i]] - i) <= k){ 11 return true; 12 } 13 } else { 14 map[nums[i]] = i; 15 } 16 } 17 return false; 18 };
时间: 2025-01-02 16:06:17