Description:
Given an array of integers, find out whether there are two distinct indices i and j in the array such that the absolute difference between nums[i] and nums[j] is at most t and the absolute difference between i and j is at most k.
Example 1:
Input: nums = [1,2,3,1], k = 3, t = 0
Output: true
Example 2:
Input: nums = [1,0,1,1], k = 1, t = 2
Output: true
Example 3:
Input: nums = [1,5,9,1,5,9], k = 2, t = 3
Output: false
思路:
题目要求:判断给定数组中是否存在两个索引下标i,j,满足 |j−i|<=k | j − i | <= k (条件1),且 |nums[j]−nums[i]|<=t | n u m s [ j ] − n u m s [ i ] | <= t (条件2)。
对条件2进行变形:
⟺|nums[j]/t−nums[i]/t|<=1
⟺
|
n
u
m
s
[
j
]
/
t
−
n
u
m
s
[
i
]
/
t
|
<=
1
(式2)
⟹|⌊nums[j]/t⌋−⌊nums[i]/t⌋|<=1
⟹
|
⌊
n
u
m
s
[
j
]
/
t
⌋
−
⌊
n
u
m
s
[
i
]
/
t
⌋
|
<=
1
(式3) (
⌊⌋
⌊
⌋
表示向下取整)
⟺⌊nums[j]/t⌋∈
⟺
⌊
n
u
m
s
[
j
]
/
t
⌋
∈
{
⌊nums[i]/t⌋−1,⌊nums[i]/t⌋,⌊nums[i]/t⌋+1
⌊
n
u
m
s
[
i
]
/
t
⌋
−
1
,
⌊
n
u
m
s
[
i
]
/
t
⌋
,
⌊
n
u
m
s
[
i
]
/
t
⌋
+
1
}(式4)
因此我们可以维护一个大小为k的字典,其中key为 ⌊num/t⌋ ⌊ n u m / t ⌋ ,value为 num n u m ,如果存在一个数 x x 满足条件2,那么这个数的key必然是{}三数之一;也就是说我们只需要验证key等于这三数对应的的value,与num的差的绝对值是否小于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
# 这里采用有序字典,它是dict的一个继承子类,按照元素输入顺序进行排序
dic = collections.OrderedDict()
for n in nums:
# 注意判断t是否为0
key = n if not t else n // t
for m in (dic.get(key - 1), dic.get(key), dic.get(key + 1)):
# 如果找到一个数满足条件一,返回
if m is not None and abs(n - m) <= t:
return True
if len(dic) == k:
# 维持字典大小为k,如果超过,删除first;函数原型:dict.popitem(last=False),不加参数表示随机从头尾删除一个
dic.popitem(False)
# 加入新数
dic[key] = n
return False