Leetcode 220. 存在重复元素 III (Contains Duplicate III)
Posted 下雨不刮风
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 220. 存在重复元素 III (Contains Duplicate III)相关的知识,希望对你有一定的参考价值。
题目
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.
Example1
Input: nums = [1,2,3,1], k = 3, t = 0
Output: true
Example2
Input: nums = [1,0,1,1], k = 1, t = 2
Output: true
Example3
Input: nums = [1,5,9,1,5,9], k = 2, t = 3
Output: true
思路
先给一个暴力解法,复杂度(O(N*K)),使用滑动窗口来求解。还能优化成(O(NlogN))
Code
class Solution:
def containsNearbyAlmostDuplicate(self, nums: List[int], k: int, t: int) -> bool:
if len(nums) < 2 or k < 1 or t < 0:
return False
if t == 0 and len(set(nums)) == len(nums):
return False
for i in range(len(nums) - 1):
# 窗口的长度为k,但不能超过数组nums的长度
for j in range(i + 1, min(len(nums), i + k + 1)):
if abs(nums[i] - nums[j]) <= t:
return True
return False
以上是关于Leetcode 220. 存在重复元素 III (Contains Duplicate III)的主要内容,如果未能解决你的问题,请参考以下文章
281.LeetCode | 220. 存在重复元素 III
Leetcode No.220 存在重复元素 III(桶排序)