[Leetcode]220. Contains Duplicate III @python

题目

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

题目要求

|nums[j] - nums[i]| <= t.

解题思路

|nums[j]nums[i]|<=t|nums[j]/tnums[i]/t|<=1|floor(nums[j]/t)floor(nums[i]/t)|<=1floor(nums[j]/t){floor(nums[i]/t1,floor(nums[i]/t),floor(nums[i]/t)+1}

floor(nums[j]/t){floor(nums[i]/t1,floor(nums[i]/t),floor(nums[i]/t)+1}
, 则|nums[j]nums[i]|<=t$|nums[j] - nums[i]| <= t$ 不成立。

代码


class Solution(object):
def containsNearbyAlmostDuplicate(self, nums, k, t):
"""
:type nums: List[int]
:type k: int
:type t: int
:rtype: bool
"""
if k < 1 or t < 0:
return False
dicts = collections.OrderedDict()

for i in range(len(nums)):
key = nums[i] / max(1,t)
for m in (key - 1,key,key + 1):
if m in dicts and abs(nums[i] - dicts[m]) <= t:
return True
dicts[key] = nums[i]
if i >= k:
dicts.popitem(last = False)
return False