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 difference between i and j is at most k.
思路
一开始题目意思理解错误,以为必须保证任何相等的数下标差不能超过k,如果是存在的很好办
首先必须存在两个数,否则返回False
建立hashtable,如果array[i]不在hashtable中,则key=array[i],value=i
如果在hashtable中,判断当前的下标i和value,如果小于等于k,则返回True,否则,value=i(缩小和后面的范围)
class Solution(object):
def containsNearbyDuplicate(self, nums, k):
hashtable={}
if len(nums)<2:
return False
for i in range(len(nums)):
if nums[i] not in hashtable:
hashtable.setdefault(nums[i],i)
else:
if i-hashtable[nums[i]]<=k:
return True
else:
hashtable[nums[i]]=i
return False