题目描述
Given an array of integers, find out whether there are two distinct indices i and j in the array such that the absolutedifference between nums[i] and nums[j] is at most t and the absolute difference between i and j is at most k.
Example 1:
1 | Input: nums = [1,2,3,1], k = 3, t = 0 |
Example 2:
1 | Input: nums = [1,0,1,1], k = 1, t = 2 |
Example 3:
1 | Input: nums = [1,5,9,1,5,9], k = 2, t = 3 |
这题时间复杂度为O(n)的方法比较巧妙,将nums里的所有数字除以t后向下取整得到modifiedNums,如果modifiedNums中有两个数字相同,那么它们一定会相差t以内,因此一定返回True,如果没有两个数字相同,那么就去查找比它小1或大1的数字,然后比较它们对应的原数字是否相差t以内。
但是这题要使用一个滑动窗口和一个字典来进行操作。滑动窗口来满足索引差值在k以内,字典的键为modifiedNums中的数字,值为nums中的数字,主要是为了查找到某个键是否在modifiedNums中(如果有直接返回True),以及方便查找原数字的值。字典操作的复杂度都为O(n)。
坑的点主要是t为0的时候,这个时候的情况和t为1的情况其实是一样的。
代码实现
1 | class Solution: |