My implementation of merging two sorted lists in linear time - what could be improved?

后端 未结 9 544
忘掉有多难
忘掉有多难 2021-01-01 04:47

Fromg Google\'s Python Class:

E. Given two lists sorted in increasing order, create and return a merged
list of all the elements in sorted order. You may mod         


        
9条回答
  •  时光说笑
    2021-01-01 05:08

    This solution runs in linear time and without editing l1 and l2:

    def merge(l1, l2):
      m, m2 = len(l1), len(l2)
      newList = []
      l, r = 0, 0
      while l < m and r < m2:
        if l1[l] < l2[r]:
          newList.append(l1[l])
          l += 1
        else:
          newList.append(l2[r])
          r += 1
      return newList + l1[l:] + l2[r:]
    

提交回复
热议问题