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.
Subscribe to see which companies asked this question
维持一个k大小的滑动窗口,需要考虑的就是边界问题,略麻烦。
判断窗口k里面是否有重复元素,可以利用集合,看看“集合化”之后,大小是否发生变化。
竟然跑出了击败99.38的速度,可见并不是很笨。
class Solution(object):
def containsNearbyDuplicate(self, nums, k):
if not nums:
return 0 < k
if len(nums) == 1 or k == 0:
return False
if len(nums) <= k:
s = set(nums)
return len(s) < len(nums)
i = 0
while i < len(nums)-k:
t = nums[i:i+k+1]
i += 1
s = set(t)
if len(s) < len(t):
return True
return False