219. 存在重复元素 II
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 1:
Input: nums = [1,2,3,1], k = 3
Output: true
Example 2:
Input: nums = [1,0,1,1], k = 1
Output: true
Example 3:
Input: nums = [1,2,3,1,2,3], k = 2
Output: false
Python代码实现:
这个做法没问题的,但是网站却出现错误实例:
class Solution:
def containsNearbyDuplicate(self, nums, k):
if len(nums)==0 or len(nums)==1:
return False
n = 0
for i in range(0, len(nums)-k):
if nums[i] - nums[i + k] == 0:
n += 1
break
if n != 0:
return True
else:
return False
错误事例:[99,99] 2 还预期 为true 明显网站错误了
网上搜的代码,可以实现:
class Solution:
def containsNearbyDuplicate(self, nums, k):
d = {}
for i in range(len(nums)):
if nums[i] in d:
if -k <= i - d[nums[i]] <= k:
return True
else:
d[nums[i]] = i
d[nums[i]] = i
return False