判斷一列數(shù)里面有沒有下標(biāo)距離<=k的兩個(gè)相同的數(shù),開個(gè)字典標(biāo)記截至目前某個(gè)數(shù)最后出現(xiàn)的下標(biāo),python字典查找復(fù)雜度O(1)
1 class Solution(object):
2 def containsNearbyDuplicate(self, nums, k):
3 """
4 :type nums: List[int]
5 :type k: int
6 :rtype: bool
7 """
8 pos = {}
9 for i in range(len(nums)):
10 if nums[i] in pos and i - pos[nums[i]] <= k:
11 return True
12 pos[nums[i]] = i
13 return False