[leetcode]219. Contains Duplicate II

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 absolute difference between i and j is at most k.

判断一个数组中有没有索引i,j,使nums[i]==nums[j]且,j-i<k

 1 class Solution(object):
 2     def containsNearbyDuplicate(self, nums, k):
 3         d = collections.defaultdict(list)
 4         for i,c in enumerate(nums):
 5             if len(d[c])>0:
 6                 l = i-max(d[c])
 7                 if l<=k:
 8                     return True
 9             d[c].append(i)
10         return False

 

posted @ 2017-03-05 21:09  wilderness  阅读(105)  评论(0编辑  收藏  举报