My simplest python solution using extend() and sort() method of array


  • 0
    F
    class Solution:
    # @param A  a list of integers
    # @param m  an integer, length of A
    # @param B  a list of integers
    # @param n  an integer, length of B
    # @return nothing(void)
    def merge(self, A, m, B, n):
        x=A[0:m]
        y=B[0:n]
        x.extend(y)
        x.sort()
        A[0:m+n]=x

  • 3
    S
    def merge(self, A, m, B, n):
            A[m:] = B[:n]
            A.sort()
    

    will work too.


  • 0
    F

    Oh, that is a another way of thinking, thanks!


  • 0
    Z

    Hi, I'm a new beginner for Python. I just want to know why
    A[0:m+n].sort()
    will not return correct order?
    Thank you


  • 0
    F

    I think the problem wants you to merge B into A, but I did not see B in your A[0:m+n].sort()
    , since I do not know your whole codes, If you can extend B after A and then sort the whole list, you should be fine.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.