leet code - 219. Contains Duplicate II
6805 ワード
219. Contains Duplicate II
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
実行時:2624ミリ秒メモリ:40.4 MB、1本のプール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データ構造を使用したランタイム:84 ms、メモリ:45 MBvar 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;
};
これは資料構造とアルゴリズムを学習する必要がある明確な例のようだ.よく復習しなければならない.
Reference
この問題について(leet code - 219. Contains Duplicate II), 我々は、より多くの情報をここで見つけました
https://velog.io/@dlawogus/leet-code-219.-Contains-Duplicate-II
テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol
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
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;
};
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;
};
Reference
この問題について(leet code - 219. Contains Duplicate II), 我々は、より多くの情報をここで見つけました https://velog.io/@dlawogus/leet-code-219.-Contains-Duplicate-IIテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol