【LeetCode】【220. Contains Duplicate III】(python版)

Description:
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.

Example 1:

Input: nums = [1,2,3,1], k = 3, t = 0
Output: true

Example 2:

Input: nums = [1,0,1,1], k = 1, t = 2
Output: true

Example 3:

Input: nums = [1,5,9,1,5,9], k = 2, t = 3
Output: false

思路:

题目要求:判断给定数组中是否存在两个索引下标i,j,满足 |ji|<=k | j − i | <= k (条件1),且 |nums[j]nums[i]|<=t | n u m s [ j ] − n u m s [ i ] | <= t (条件2)。

对条件2进行变形:
|nums[j]/tnums[i]/t|<=1 ⟺ | n u m s [ j ] / t − n u m s [ i ] / t | <= 1 (式2)
|nums[j]/tnums[i]/t|<=1 ⟹ | ⌊ n u m s [ j ] / t ⌋ − ⌊ n u m s [ i ] / t ⌋ | <= 1 (式3) ( ⌊ ⌋ 表示向下取整)
nums[j]/t ⟺ ⌊ n u m s [ j ] / t ⌋ ∈ { nums[i]/t1,nums[i]/t,nums[i]/t+1 ⌊ n u m s [ i ] / t ⌋ − 1 , ⌊ n u m s [ i ] / t ⌋ , ⌊ n u m s [ i ] / t ⌋ + 1 }(式4)

因此我们可以维护一个大小为k的字典,其中key为 num/t ⌊ n u m / t ⌋ ,value为 num n u m ,如果存在一个数 x x 满足条件2,那么这个数的key必然是{num/t1,num/t,num/t+1}三数之一;也就是说我们只需要验证key等于这三数对应的的value,与num的差的绝对值是否小于t。

实现代码如下:

class Solution(object):
    def containsNearbyAlmostDuplicate(self, nums, k, t):
        """
        :type nums: List[int]
        :type k: int
        :type t: int
        :rtype: bool
        """
        # 检验数据合法性
        if k < 1 or t < 0:
            return False
        # 这里采用有序字典,它是dict的一个继承子类,按照元素输入顺序进行排序
        dic = collections.OrderedDict()
        for n in nums:
            # 注意判断t是否为0
            key = n if not t else n // t
            for m in (dic.get(key - 1), dic.get(key), dic.get(key + 1)):
                # 如果找到一个数满足条件一,返回
                if m is not None and abs(n - m) <= t:
                    return True
            if len(dic) == k:
                # 维持字典大小为k,如果超过,删除first;函数原型:dict.popitem(last=False),不加参数表示随机从头尾删除一个
                dic.popitem(False)
            # 加入新数
            dic[key] = n
        return False
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值