219. Contains Duplicate 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.
思路:
首先是要找到列表中可能存在的重复的值,然后重复的值之间的序号差的绝对值是否小于等于k,直接用for(不用enumerate)查找重复的值,再去查找下标,再比较,情况很多,很麻烦。这里考虑使用字典,把值作为Key,该值对应的下标作为Value,若有相同的值则Key想用直接比较Value的差值,有一个满足条件的直接返回True,否则返回False即可。
参考代码:
class Solution:
def containsNearbyDuplicate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: bool
"""
dic = {}
for i, v in enumerate(nums):
if v in dic and i - dic[v] <= k:
return True
dic[v] = i
return False