leetcode219.存在重复元素 II

120 阅读1分钟

219.存在重复元素 II

给定一个整数数组和一个整数 k,判断数组中是否存在两个不同的索引 ij

nums [i] = nums [j],且| i - j |<= k

输入: nums = [1,2,3,1,2,3], k = 2
输出: false
class Solution:  # 找同数字最小间隔,若不超过 k 则满足条件
    def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
        hash = {}  # hash表
        for i in range(len(nums)):
            if nums[i] not in hash:  # 若nums[i]不在hash中
                hash[nums[i]] = i  # 键 :值 = 数字 :下标
            else:  # 若已存在
                if i - hash[nums[i]] <= k:
                    return True
                else:  # 若下标差>k
                    hash[nums[i]] = i  # 将索引更新为当前索引
        return False