220 Contains Duplicate III

220 Contains Duplicate III 

这道题用dic来记录上一次桶区间内的下标,唯一的trick是比较周边的一共三个桶

class Solution:
    # @param {integer[]} nums
    # @param {integer} k
    # @param {integer} t
    # @return {boolean}
    def containsNearbyAlmostDuplicate(self, nums, k, t):
        if k <= 0 or t < 0:
            return False
        dic = {}
        for i in xrange(len(nums)):
            b = nums[i]/(t+1)
            for v in [b-1,b,b+1]:
                if v in dic and abs(nums[dic[v]]-nums[i]) <= t:
                    return True
            dic[b] = i
            if i >= k:
                del dic[nums[i-k]/(t+1)]
        return False

 

posted @ 2015-08-07 02:46  dapanshe  阅读(130)  评论(0编辑  收藏  举报