Skip to content

Latest commit

 

History

History
40 lines (32 loc) · 770 Bytes

219. 存在重复元素 II.md

File metadata and controls

40 lines (32 loc) · 770 Bytes

给定一个整数数组和一个整数 k,判断数组中是否存在两个不同的索引 i 和 j,使得 nums [i] = nums [j],并且 i 和 j 的差的绝对值最大为 k。

示例 1:

输入: nums = [1,2,3,1], k = 3
输出: true

示例 2:

输入: nums = [1,0,1,1], k = 1
输出: true

示例 3:

输入: nums = [1,2,3,1,2,3], k = 2
输出: false

solution:

/**
 * @param {number[]} nums
 * @param {number} k
 * @return {boolean}
 */
var containsNearbyDuplicate = function(nums, k) {
    const record = {}
    for (let i = 0,len = nums.length; i < len; i++) {
        if (record[nums[i]] !== undefined && (i - record[nums[i]]) <= k) return true
        record[nums[i]] = i
    }
    return false
};