leet code - 219. Contains Duplicate II


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 MB
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;
};
これは資料構造とアルゴリズムを学習する必要がある明確な例のようだ.よく復習しなければならない.