接上次的Contains Duplicate,这次的ii的难度变大了。要求看是否2个一样的数的index之差小于指定的k。还是用的Counter方法,先求出了所有的重复值。然后针对每个重复值来返回去求index,最后收录在一个list里。最后求相互之间的差值。代码如下:
class Solution(object):
def containsNearbyDuplicate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: bool
"""
from collections import Counter
list1 = Counter(nums)
for i in list1.keys():
list2 = []
if list1[i] > 1:
for h in range(len(nums)):
if nums[h] == i:
list2.append(h)
a = list2[0]
for i in range(1,len(list2)):
if list2[i] - a <= k:
return True
else:
a = list2[i]
if i == len(list2) - 1:
break
else:
return False