Last active
July 17, 2019 00:24
-
-
Save andersonleite/ac6b77a75d3bed621166495e346ffd7d to your computer and use it in GitHub Desktop.
Distinct indices
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Given an array of integers nums and an integer k, determine whether there are two distinct indices i and j in the array where nums[i] = nums[j] and the absolute difference between i and j is less than or equal to k. | |
// Example | |
// For nums = [0, 1, 2, 3, 5, 2] and k = 3, the output should be | |
// containsCloseNums(nums, k) = true. | |
// There are two 2s in nums, and the absolute difference between their positions is exactly 3. | |
// For nums = [0, 1, 2, 3, 5, 2] and k = 2, the output should be | |
// containsCloseNums(nums, k) = false. | |
// The absolute difference between the positions of the two 2s is 3, which is more than k. | |
function containsCloseNums(nums, k) { | |
let map = new Map() | |
for(let i=0; i < nums.length; i++){ | |
if(map.get(nums[i])!==null && i - map.get(nums[i]) <= k){ | |
return true | |
} | |
map.set(nums[i], i) | |
} | |
return false | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment