Leetcode 220. Duplicate element III (Contains Duplicate III)

topic

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

Thinking

Give a solution of violence, complexity \ (O (N * K) \) , using a sliding window to solve. But also optimized to \ (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

Guess you like

Origin www.cnblogs.com/yufeng97/p/12602295.html