包含重复II

时间:2018-10-25 13:17:52

标签: python python-3.x list

给定一个整数数组和一个整数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有问题。但是我不知道为什么这行不通。

1 个答案:

答案 0 :(得分:0)

进行一些小的调整以使其起作用:

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)

或者使用一些不错的工具,例如anyenumerate,或者没有昂贵的弹出和递归操作:

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