时间:2020-10-11
题目地址:https://leetcode-cn.com/problems/contains-duplicate-iii/
题目难度:Medium
题目描述:
在整数数组 nums 中,是否存在两个下标 i 和 j,使得 nums [i] 和 nums [j] 的差的绝对值小于等于 t ,且满足 i 和 j 的差的绝对值也小于等于 ķ 。
如果存在则返回 true,不存在返回 false。
示例 1:
输入: nums = [1,2,3,1], k = 3, t = 0
输出: true
示例 2:
输入: nums = [1,0,1,1], k = 1, t = 2
输出: true
示例 3:
输入: nums = [1,5,9,1,5,9], k = 2, t = 3
输出: false
思路1:暴力 + 剪枝
直接暴力求解的基础上,优化剪枝 j从 i+1 到 min(len(nums), i + k + 1)
代码段1:超时
class Solution:
def containsNearbyAlmostDuplicate(self, nums: List[int], k: int, t: int) -> bool:
length = len(nums)
for i in range(0, max(length - k, length)):
temp = min(i + k + 1, length)
for j in range(i + 1, temp):
if abs(nums[i] - nums[j]) <= t:
return True
return False
看下我一开始写的,为啥逻辑混乱呢???
class Solution:
def containsNearbyAlmostDuplicate(self, nums: List[int], k: int, t: int) -> bool:
length = len(nums)
for i in range(0, max(length - k, length)):
j = min(i + k, length - 1)
for each_i in range(i, j + 1):
for each_j in range(i + 1, j + 1):
if each_i != each_j:
if each_j - each_i <= k and abs(nums[each_i] - nums[each_j]) <= t:
return True
return False
总结:
暴力求解不可行
思路2:二叉搜索树
代码段2:通过
from sortedcontainers import SortedSet
class Solution:
def containsNearbyAlmostDuplicate(self, nums: List[int], k: int, t: int) -> bool:
sorted_set = SortedSet()
for i in range(len(nums)):
num = nums[i]
if sorted_set and sorted_set.bisect_left(num) < len(sorted_set):
if sorted_set[sorted_set.bisect_left(num)] <= num + t:
return True
if sorted_set and sorted_set.bisect_left(num) != 0:
if num <= sorted_set[sorted_set.bisect_left(num) - 1] + t:
return True
sorted_set.add(num)
if len(sorted_set) > k:
sorted_set.remove(nums[i - k])
return False
总结:
python很方便
思路3:滑动窗口
代码段3:通过
from sortedcontainers import SortedSet
class Solution:
def containsNearbyAlmostDuplicate(self, nums: List[int], k: int, t: int) -> bool:
n = len(nums)
if n <= 1:
return False
record = set()
for i in range(n):
if t == 0:
if nums[i] in record:
return True
else:
for j in record:
if abs(j - nums[i]) <= t:
return True
record.add(nums[i])
if len(record) > k:
record.remove(nums[i-k])
return False
总结:
一开始不知道咋写,是因为卡在判断哪里了,nums[i], t, k的判断都有点问题
桶排序https://leetcode-cn.com/problems/contains-duplicate-iii/solution/li-yong-tong-de-yuan-li-onpython3-by-zhou-pen-chen/