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

猜你喜欢

转载自www.cnblogs.com/yufeng97/p/12602295.html