标签:problem 索引 com rom bool targe http enum nta
方法一:
class Solution:
def containsNearbyDuplicate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: bool
"""
d = dict()
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
思路:
创建dict
遍历list
if items in dict 比较索引
如果不在 item添加到dict
方法二:
class Solution:
def containsNearbyDuplicate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: bool
"""
if nums == [] or k <=0:
return False
d = {}
for i,x in enumerate(nums):
if x in d and i - d[x] <= k:
return True
d[x] = i
return False
思路与上面的方法相近。
enumerate作用于list,str,tuple能够同时列出索引和数据。
标签:problem 索引 com rom bool targe http enum nta
原文地址:https://www.cnblogs.com/xiaojianliu/p/10034533.html