Question:
Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k.
Example:
Input: nums = [1,2,3,1], k = 3
Output: true
Input: nums = [1,0,1,1], k = 1
Output: true
Input: nums = [1,2,3,1,2,3], k = 2
Output: false
Solution:
/**
* @param {number[]} nums
* @param {number} k
* @return {boolean}
*/
var containsNearbyDuplicate = function(nums, k) {
for ( let i=0; i<nums.length; i++ ) {
for ( let j=1; j<k+1; j++ ) {
if ( i+j<nums.length && nums[i+j] === nums[i] ) {
return true;
}
if ( i-j >= 0 && nums[i-j] === nums[i] ) {
return true;
}
}
}
return false
};
Runtime: 3804 ms, faster than 2.74% of JavaScript online submissions for Contains Duplicate II.