#-*- coding: UTF-8 -*-
#遍历所有元素,将元素值当做键、元素下标当做值
#存放在一个字典中。遍历的时候,
#如果发现重复元素,则比较其下标的差值是否小于k,
#如果小于则可直接返回True,否则更新字典中该键的值为新的下标
class Solution(object):
def containsNearbyDuplicate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: bool
"""
num_map={}
for i in xrange(len(nums)):
if nums[i] in num_map and i-num_map[nums[i]]<=k:
return True
else:
num_map[nums[i]]=i
return False
sol=Solution()
print sol.containsNearbyDuplicate([1,0,1,1], 1)
相关文章
- 02-16Leetcode 219. Contains Duplicate II
- 02-16[Leetcode]220. Contains Duplicate III
- 02-16LeetCode217 Contains Duplicate
- 02-16LeetCode-220 Contains Duplicate III
- 02-16力扣 LeetCode 219. 存在重复元素 II
- 02-16219. 存在重复元素 II - 力扣(LeetCode)
- 02-16[leetcode]Word Ladder II @ Python
- 02-16【LeetCode】375. Guess Number Higher or Lower II 解题报告(Python)
- 02-16[leetcode]Best Time to Buy and Sell Stock II @ Python
- 02-16[Leetcode][Python]45: Jump Game II