Leetcode: . 存在重复元素 III

. 存在重复元素 III


给定一个整数数组,判断数组中是否有两个不同的索引 i 和 j,使得 nums [i] 和 nums [j] 的差的绝对值最大为 t,并且 i 和 j 之间的差的绝对值最大为 ķ。

示例 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

自己没做出来,看了别人的题解,技巧性在于t = 0 时的判断,不然会超时。。。

Python

class Solution:
    def containsNearbyAlmostDuplicate(self, nums, k, t):
        """
        :type nums: List[int]
        :type k: int
        :type t: int
        :rtype: bool
        """
        if len(nums) == 0 or k == 0:
            return False
        tmp = set()
        tmp.add(nums[0])
        for i in range(1,len(nums)):
            if t == 0:
                if nums[i] in tmp:
                    return True
            else:
                for j in tmp:
                    if abs(nums[i] - j) <= t:
                        return True;
            tmp.add(nums[i]) # 把当前这个元素加入到set中。
            if len(tmp) > k:
                tmp.remove(nums[i-k])
        return False
原文地址:https://www.cnblogs.com/xmxj0707/p/9699266.html