包含副本II

2024-04-19 17:26:27 发布

您现在位置:Python中文网/ 问答频道 /正文

给定一个整数数组和一个整数k,找出数组中是否有两个不同的指数i和j,使得nums[i]=nums[j],i和j之间的绝对差最多为k

例1:

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

例2:

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

例3:

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

这是我的密码:

class Solution(object):
def containsNearbyDuplicate(self, nums, k):
    """
    :type nums: List[int]
    :type k: int
    :rtype: bool
    """
    def helper(lnums, n):
        if len(lnums) == 0 and n == 0:
            return False
        elif len(lnums) > n:
            for i in lnums[1:n]:
                if i == lnums[0]:
                    return True
            lnums.pop(0)
            return helper(lnums, n)
        else:
            return False

    return helper(nums, k)

有人能指出我为什么做错了吗???我知道elif有问题。但我不知道为什么这样不行。你知道吗


Tags: helperfalsetrueinputoutputlenreturnif
1条回答
网友
1楼 · 发布于 2024-04-19 17:26:27

一些小的调整,使其工作:

def helper(lnums, n):
    if len(lnums) == 0 or n == 0:  # note: or, not and
        return False
    else:   # there do NOT have to be at least n elements, why would there?
        for i in lnums[1:n+1]:  # exclusive upper slice boundary -> n+1
            if i == lnums[0]:
                return True
        lnums.pop(0)
        return helper(lnums, n)

或者不使用昂贵的弹出和递归,使用一些精细的util,如^{}^{}

def helper(lnums, n):
    return any(x in lnums[i+1:i+1+n] for i, x in enumerate(lnums))

相关问题 更多 >