leetcode-219题:contains duplicateii

题目

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

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution(object):
def containsNearbyDuplicate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: bool
"""
if nums==None or len(nums)<2 or k<1:
return False
num_indices = {}
for i,n in enumerate(nums):
if n not in num_indices:
num_indices[n] = i
else:
if i-num_indices[n] <= k:
return True
num_indices[n] = i
return False