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

前端 未结 10 749

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:16

    Not that clever, not O(n), could use a bit of optimization. But it works.

    def longest(seq):
      result = []
      for v in seq:
        for l in result:
          if v == l[-1] + 1:
            l.append(v)
        else:
          result.append([v])
      return max(result, key=len)
    

提交回复
热议问题