存在重复数II

给你一个整数数组 nums 和一个整数 k ,判断数组中是否存在两个 不同的索引 i 和 j ,满足 nums[i] == nums[j] 且 abs(i - j) <= k 。如果存在,返回 true ;否则,返回 false 。

/**
 * 时间复杂度O(n^2)
 */
const containsNearbyDuplicate = (nums = [1, 2, 3, 1], k = 3) => {
    let len = nums.length
    for (let i = 0; i < len; i++) {
        const v = nums[i]
        const index = nums.indexOf(v, i + 1)
        if (index !== -1 && Math.abs(i - index) <= k) {
            return true
        }
    }
    return false
};

/**
 * 时间复杂度O(n)
 */
const containsNearbyDuplicate = (nums = [1, 2, 3, 1], k = 3) => {
    const len = nums.length
    const hash = []
    for (let i = 0; i < len; i++) {
        const v = nums[i]
        if (hash.includes(v)) {
            return true
        }
        hash.push(v)
        if (hash.length > k) {
            hash.shift()
        }
    }
    return false
};

/**
 * 使用set优化
 */
const containsNearbyDuplicate = (nums = [1, 2, 3, 1], k = 3) => {
    const len = nums.length
    const set = new Set()
    for (let i = 0; i < len; i++) {
        const v = nums[i]
        if (set.has(v)) {
            return true
        }
        set.add(v)
        if (set.size > k) {
            set.delete(nums[i - k])
        }
    }
    return false
};

  

posted @ 2023-02-05 02:05  671_MrSix  阅读(10)  评论(0编辑  收藏  举报