字符串中最长的锯齿形子序列

时间:2020-07-15 18:36:24

标签: python zigzag

如何优化下面为该问题编写的代码?我可以得到一些建议吗?

给出一个整数元素数组,找到最长子序列的长度,以使所有元素交替出现。如果序列{x1,x2,.. xn}是交替序列,则其元素满足以下关系之一:

x1 < x2 > x3 < x4 > x5 < …. xn 

x1 > x2 < x3 > x4 < x5 > …. xn

输入

8
10 22 9 33 49 50 31 60

其中:第一行表示数组中元素的数量。 第二行代表数组元素。

输出

6

说明

子序列{10, 22, 9, 33, 31, 60}的格式为x1 < x2 > x3 < x4 > x5 < x6,即{ 10 < 22 > 9 < 33 > 31 < 60 },它是这种形式中最大的子序列,该子序列的长度为6,因此输出{ {1}}。

6

2 个答案:

答案 0 :(得分:2)

您可以迭代列表,同时保留对以前的节点没有影响的引用。

我们首先将prev_node设置为列表中的第一个元素。 循环从索引1开始,并迭代到结束。对于每个值,它将值与prev_node进行比较。如果是交替模式,请增加max_lenght并更新prev_node。

LT = -1     # Less than
GT = 1      # Greater than

max_length = 1
prev_node = L[0]       # Begin at 0
prev_compare = 0
found = 0
for i in range(1, len(L)):
    if L[i] < prev_node:
        if prev_compare != LT:
            prev_compare = LT
            found = True
    elif L[i] > prev_node:
        if prev_compare != GT:
            prev_compare = GT
            found = True
    # If an alternating node is found
    if found:
        max_length += 1
        prev_node = L[i]
        found = False

print(max_length)
  • 时间复杂度: O(n),因为它仅遍历列表一次。
  • 空间复杂度: O(1),因为(其他)内存使用量不取决于输入大小。

编辑#1

根据您的评论,我认为您不太在乎代码的可读性。

我有一个与上述相同算法的简短版本(就字符数而言)。逻辑基本相同,因此性能也相同。

nodes = [L[0]]
prev_compare = -1
for e in L[1:]:
    if e != nodes[-1] and (e > nodes[-1]) != prev_compare:
        prev_compare = e > nodes[-1]
        nodes += [e]

print(len(nodes))

答案 1 :(得分:1)

您可以使用生成器执行以下检查:

  • 是否连续两个数字yx < y都认为<
  • 两个连续的c1c2是否交替,即c1 != c2

然后,您可以找到第二个校验为True的最长子序列。在这里,我们需要考虑到两个检查都从原始序列中消耗了一个“长度单位”,即,如果我们发现两个连续的<比较是交替的,则将由一个True表示,但是是通过两次比较生成的。而这两个比较又是由三个连续的数字生成的。因此,我们可以通过在最终结果中添加2来解决这个问题。

这是一个代码示例:

import itertools as it
from more_itertools import pairwise

numbers = [...]  # input goes here

less_than = (x < y for x, y in pairwise(numbers))
alternating = (x != y for x, y in pairwise(less_than))
lengths = (
    sum(1 for _ in g)  # length of sub-sequence
    for k, g in it.groupby(alternating)
    if k  # check if it's an alternating sub-sequence
)
result = max(lengths, default=-1) + 2
相关问题