leetcode-存在重复元素 II

219. 存在重复元素 II

题解:

可以使用哈希表来解决这个问题。遍历数组,对于每个元素,检查它是否已经在哈希表中出现过,如果出现过,则判断当前索引与哈希表中存储的索引之差是否小于等于k,如果是,则返回true;否则,将当前元素及其索引存入哈希表中。如果遍历完整个数组都没有找到满足条件的两个索引,则返回false。

class Solution:
    def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
        table = {}
        for i, num in enumerate(nums):
            if num in table and i - table[num] <= k:
                return True
            table[num] = i
        return False

你可能感兴趣的:(leetcode)