1319. Contains Duplicate II
Description
Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k.
Example
Given nums = [1,2,1], k = 0, return false.
Code:
1.
def containsNearbyDuplicate(self, nums, k):
# Write your code here
for i in range(len(nums)-k):
for j in range(i+1, i+k+1):
if nums[i] == nums[j]:
return True
return False
时间复杂度过高
2.
def containsNearbyDuplicate(self, nums, k):
# Write your code here
res = {}
for i in range(len(nums)):
if nums[i] in res is not None and i-res[nums[i]]<=k:
return True
else:
res[nums[i]] = i
return False