码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 220. 存在重复元素 III (Contains Duplicate III)

时间:2020-03-31 01:13:11      阅读:88      评论:0      收藏:0      [点我收藏+]

标签:nlog   find   dice   integer   contain   most   ice   lock   NPU   

题目

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)

标签:nlog   find   dice   integer   contain   most   ice   lock   NPU   

原文地址:https://www.cnblogs.com/yufeng97/p/12602295.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!