# 219. Contains Duplicate II *

Given an array of integers and an integer k, find out whether there are two distinct indicesi and j in the array such that nums[i] = nums[j] and the difference betweeni and j is at most k.

My code:

Wrong (Time exceeded)

class Solution(object):
def containsNearbyDuplicate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: bool
"""
n = len(nums)
dict ={}
for i in range(n):
if nums[i] in dict.keys():
dict[nums[i]].append(i)
else:
dict[nums[i]]=[i]
for key in dict.keys():
keyLen= len(dict[key])
for j in range(keyLen-1):
if dict[key][j+1] - dict[key][j] <=k:
return True
return False

Wrong (Time exceeded)
class Solution(object):
def containsNearbyDuplicate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: bool
"""
n = len(nums)
currentList=[]
for i in range(n):
if i > k:
currentList.pop(0)
if nums[i] in currentList:
return True
else:
currentList.append(nums[i])
return False

Accepted:

class Solution(object):
def containsNearbyDuplicate(self, nums, k):
dic = {}
for i, v in enumerate(nums):
if v in dic and i - dic[v] <= k:
return True
dic[v] = i
return False

• 本文已收录于以下专栏：

举报原因： 您举报文章：219. Contains Duplicate II * 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)