在哈希表的基础上扫描判断,代码如下:
class Solution(object):
def containsNearbyDuplicate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: bool
"""
if len(nums) == 0 or len(nums) == 1:
return False
if k == 0:
return False
dic = {}
for n in nums:
if n not in dic:
dic[n] = 1
else:
dic[n] += 1
visit = [0 for i in range(len(nums))]
for i in range(len(nums)):
if dic[nums[i]] > 1:
print "here"
visit[i] = 1
index1 = i
for j in range(i+1, len(nums)):
if nums[j] == nums[i]:
if j - i <= k:
return True
return False