In python, how does one efficiently find the largest consecutive set of numbers in a list that are not necessarily adjacent?

前端 未结 10 746

For instance, if I have a list

[1,4,2,3,5,4,5,6,7,8,1,3,4,5,9,10,11]

This algorithm should return [1,2,3,4,5,6,7,8,9,10,11].

To cl

10条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-31 12:03

    You can use The Patience Sort implementation of the Largest Ascending Sub-sequence Algorithm

    def LargAscSub(seq):
        deck = []
        for x in seq:
            newDeck = [x]
            i = bisect.bisect_left(deck, newDeck)
            deck[i].insert(0, x) if i != len(deck) else deck.append(newDeck)
        return [p[0] for p in deck]
    

    And here is the Test results

    >>> LargAscSub([1,4,2,3,5,4,5,6,7,8,1,3,4,5,9,10,11])
    [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
    >>> LargAscSub([1, 2, 3, 11, 12, 13, 14])
    [1, 2, 3, 11, 12, 13, 14]
    >>> LargAscSub([11,12,13,14])
    [11, 12, 13, 14]
    

    The Order of Complexity is O(nlogn)

    There was one note in the wiki link where they claimed that you can achieve O(n.loglogn) by relying on Van Emde Boas tree

提交回复
热议问题