Code golf: combining multiple sorted lists into a single sorted list

前端 未结 26 2016
余生分开走
余生分开走 2020-12-29 12:42

Implement an algorithm to merge an arbitrary number of sorted lists into one sorted list. The aim is to create the smallest working programme, in whatever language you like.

26条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-29 12:54

    Python, 181 chars


    from heapq import *
    def m(l):
     r=[]
     h=[]
     for x in l:
      if x:
       heappush(h, (x[0], x[1:]))
     while h:
      e,f=heappop(h)
      r.append(e)
      if f:
       heappush(h, (f.pop(0),f))
     return r
    

    This runs in O(NlgM) time, where N is the total number of items and M is the number of lists.

提交回复
热议问题