# 219. Contains Duplicate II *

60人阅读 评论(0)

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

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：61564次
• 积分：3906
• 等级：
• 排名：第8618名
• 原创：332篇
• 转载：90篇
• 译文：0篇
• 评论：11条
最新评论