Given an integer array nums and an integer k, return true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i - j) <= k.
Example 1:
Input: nums = [1,2,3,1], k = 3
Output: true
Example 2:
Input: nums = [1,0,1,1], k = 1
Output: true
Example 3:
Input: nums = [1,2,3,1,2,3], k = 2
Output: false
Constraints:
1 <= nums.length <= 105
-109 <= nums[i] <= 109
0 <= k <= 105
풀이 1 브루트 포스로 Runtime: 2624 ms Memory: 40.4 MB
var containsNearbyDuplicate = function(nums, k) {
let list = [];
for(let i = 0; i < nums.length-1; i++){
for(let j = i+1; j < nums.length; j++){
if(nums[i] === nums[j] && Math.abs(i-j) < Math.min(...list)){
list.push(Math.abs(i-j))
}
}
}
return Math.min(...list) <= k;
};
풀이 2 Map자료구조이용 Runtime : 84ms, Memory : 45MB
var containsNearbyDuplicate = function(nums, k) {
let m = new Map();
for(let i = 0; i < nums.length; i++){
if(i - m.get(nums[i]) <= k){
return true;
}
m.set(nums[i],i);
}
return false;
};
자료구조와 알고리즘을 공부해야 하는 명확한 예를 보여주는 문제 같다. 자주자주 복습해야겠다.