###### 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

#### 【LeetCode-面试算法经典-Java实现】【219-Contains Duplicate II（包含重复元素II）】

2015-08-29 06:36:21

#### leetcode 219: Contains Duplicate II

2015-05-29 15:02:09

#### leetcode_c++：Contains Duplicate II(219)

2016-06-18 13:33:40

#### 219. Contains Duplicate II [easy] (Python)

2016-06-14 19:59:14

#### LeetCode219 ContainsDuplicateII java题解

2015-07-02 17:50:06

#### LeetCode 219. Contains Duplicate II（C++版）

2017-03-31 13:39:15

#### LeetCode 219:Contains Duplicate II

2015-05-31 18:41:22

#### leetcode 219 Contains Duplicate II C++

2016-06-05 15:09:27

#### [leetcode-219]Contains Duplicate II（Ｃ）

2015-08-26 11:03:54

#### 219. Contains Duplicate II

2015-06-03 16:58:33

## 不良信息举报

219. Contains Duplicate II *