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

前端 未结 10 750

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

    Warning: This is the cheaty way to do it (aka I use python...)

    import operator as op
    import itertools as it
    
    def longestSequence(data):
    
        longest = []
    
        for k, g in it.groupby(enumerate(set(data)), lambda(i, y):i-y):
            thisGroup = map(op.itemgetter(1), g)
    
            if len(thisGroup) > len(longest):
                longest = thisGroup
    
        return longest
    
    
    longestSequence([1,4,2,3,5,4,5,6,7,8,1,3,4,5,9,10,11, 15,15,16,17,25])
    

提交回复
热议问题