繁体   English   中英

找到最长的递增子数组

[英]Find the longest increasing subarray

例如:输入 = [1,2,3,1,5,7,8,9],输出 = [1,5,7,8,9]

找出最长的连续递增子数组

我自己试过这样的:

def longsub(l):
    newl = []
    for i in range(len(l)) :
        if l[i] < l[i+1] :
            newl.append(l[i])
        else :
            newl = []
    return newl

但是由于列表索引超出范围,它会出错。 (它无法获得最后一个值之后的值)

def longsub(l):
    newl = []
    for i in range(len(l)) :
        if l[i] > l[i-1] :
            newl.append(l[i])
        else :
            newl = []
    return newl

然后我这样做了,但我会得到没有增加子数组的第一个值的结果。

我应该如何纠正我的代码? 谢谢!

假设您有这个助手供您使用:

def increasing_length_at(l, i):
    """Returns number of increasing values found at index i.

    >>> increasing_length_at([7, 6], 0)
    1
    >>> increasing_length_at([3, 7, 6], 0)
    2
    """
    val = l[i] - 1
    for j in range(i, len(l)):
        if l[j] <= val:  # if non-increasing
            break
        val = l[j]
    return j - i

您如何将其用作解决方案的一部分?

您可以使用 2 个loops (第一个循环遍历输入,第二个循环从第一个循环的索引开始循环直到结束):

inp = [1,2,3,1,5,7,8,9]
output = [1,5,7,8,9]

i, res = 0, []

while i < len(inp):
    tempResult = [startNum := inp[i]] # Python>3.8: Walrus operator
    for j in range(i+1, len(inp)):
        if startNum > inp[j]:
            i = j-1 # skip already compared items!
            break
        tempResult.append(startNum := inp[j]) # Python>3.8: Walrus operator
    if len(tempResult) > len(res):
        res = tempResult
    i += 1

print(res, res == output)

出去:

[1, 5, 7, 8, 9] True

首先,您可以使用len(l) - 1来避免IndexError 但是,您的方法无效,因为这只会返回最后一个增加的子项。 这是我的方法:

def longsub(l):
    res, newl = [], []
    for i in range(len(l)-1):
        if l[i] < l[i+1]:
            newl.append(l[i])
        else:
            newl.append(l[i])
            res.append(newl)
            newl = []
    if newl: res.append(newl)
    return max(res, key=len)
input = [1,2,3,4,5,1,5,7,8,9]
print(longsub(input))

输出:

>>> [1, 2, 3, 4, 5]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM