219. Contains Duplicate II
2016-08-01 本文已影响15人
oo上海
219. Contains Duplicate II
题目:
https://leetcode.com/problems/contains-duplicate-ii/
难度:
Easy
经过了Contains Duplicate的考验,用hash table(也叫dictionary)来存,这个元素还没出现过,就放hash table,如果出现了,计算相邻距离,小于等于k则return true,否则更新hash table中元素的位置,
我用的sort
class Solution(object):
def containsNearbyDuplicate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: bool
"""
if len(nums) < 2 : return False
lookup = {}
for i in range(len(nums)):
if nums[i] not in lookup:
lookup[nums[i]] = i
else:
if i - lookup[nums[i]] <= k :
return True
lookup[nums[i]] = i
return False