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

后端 未结 9 593
忘掉有多难
忘掉有多难 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:14

    According to a note here:

    # Note: the solution above is kind of cute, but unforunately list.pop(0)
    # is not constant time with the standard python list implementation, so
    # the above is not strictly linear time.
    # An alternate approach uses pop(-1) to remove the endmost elements
    # from each list, building a solution list which is backwards.
    # Then use reversed() to put the result back in the correct order. That
    # solution works in linear time, but is more ugly.    
    

    and this link http://www.ics.uci.edu/~pattis/ICS-33/lectures/complexitypython.txt

    append is O(1), reverse is O(n) but then it also says that pop is O(n) so which is which? Anyway I have modified the accepted answer to use pop(-1):

    def linear_merge(list1, list2):
        # +++your code here+++
        ret = []
        while list1 and list2:
            if list1[-1] > list2[-1]:
                ret.append(list1.pop(-1))
            else:
                ret.append(list2.pop(-1))
    
        ret.reverse()
    
        return list1 + list2 + ret
    

提交回复
热议问题