题目
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.
题目要求
给定一个数组,判断数组中是否存在两个不同位置i,j的元素,j - i <= k,
|nums[j] - nums[i]| <= t.
解题思路
此题参考了书影博客的解题思路。
|nums[j]−nums[i]|<=t⇒|nums[j]/t−nums[i]/t|<=1⇒|floor(nums[j]/t)−floor(nums[i]/t)|<=1⇒floor(nums[j]/t)∈{floor(nums[i]/t−1,floor(nums[i]/t),floor(nums[i]/t)+1}
如果
floor(nums[j]/t)∉{floor(nums[i]/t−1,floor(nums[i]/t),floor(nums[i]/t)+1}
, 则
|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