Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array s;uch that nums[i] = nums[j]and the absolute difference between i and j is at most k.
思路:
使用一個map來存放元素登疗,enumerate函數(shù)用于遍歷序列中的元素以及它們的下標氏豌。當元素沒在map中辽装,組成一個item谎亩,index對叮趴。繼續(xù)遍歷戒傻。如果發(fā)現(xiàn)元素在map中纸泄,然后兩者之差小于k,則說明存在這樣的元素對幅慌。
class Solution(object):
def containsNearbyDuplicate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: bool
"""
d = {}
for index, item in enumerate(nums):
if item in d and index - d[item] <= k:
return True
else:
d[item] = index
print d
return False