暴搜的话,在k大的时候是O(n**2)的复杂度,会超时.
采用一个字典来记录每个value的位置.O(N)
class Solution: def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool: table = {} for i, v in enumerate(nums): if table.get(v, -1) == -1: table[v] = i else: if i - table[v] <= k: return True else: table[v] = i return False