查找连续数字序列

时间:2011-10-31 15:16:19

标签: algorithm math

如何在数组数组中找到最长的连续数字序列?每个数字数组代表结果序列中的一个或零个数字。

示例([] - 表示数组(如javascript中)):

[
    [1, 5, 6],
    [7],
    [22, 34],
    [500, 550],
    [60, 1],
    [90, 100],
    [243],
    [250, 110],
    [150],
    [155],
    [160]
]

正确的输出是:[1, 7, 22, 60, 90, 110, 150, 155, 160]

详细输出:

1,   -- index  1 all 1, 5 and 6 would match here, pick the smallest
7,   -- index  2
22,  -- index  3
     -- index  4 skipped, the sequence would end here or wouldn't be the longest possible
60,  -- index  5 picked 60, because 1 wouldn't continue in the sequence
90,  -- index  6
     -- index  7 skipped, the sequence would end here or wouldn't be the longest possible
110, -- index  8
150, -- index  9
155, -- index 10
160  -- index 11

1 个答案:

答案 0 :(得分:1)

一种可能的方法是使用动态编程作为参数,考虑最后一个值和第一个子数组的索引。

这是Python中基于递归和memoization的解决方案

data = [[1, 5, 6],
        [7],
        [22, 34],
        [500, 550],
        [60, 1],
        [90, 100],
        [243],
        [250, 110],
        [150],
        [155],
        [160]]

def longest(x0, i, _cache=dict()):
    if i == len(data):
        return []
    try:
        return _cache[x0, i]
    except KeyError:
        best = longest(x0, i+1)
        for x in data[i]:
            if x >= x0:
                L = [x] + longest(x, i+1)
                if len(L) > len(best):
                    best = L
        _cache[x0, i] = best
        return best

print longest(0, 0)