Merge Two Sorted Arrays

Merge two given sorted integer array A and B into a new sorted integer array.

Example

A=[1,2,3,4]

B=[2,4,5,6]

return [1,2,2,3,4,4,5,6]

Solution:

class Solution:
    #@param A and B: sorted integer array A and B.
    #@return: A new sorted integer array
    def mergeSortedArray(self, A, B):
        # write your code her
        i , j = 0, 0
        k = 0
        list = [0] * (len(A) + len(B))
        while i < len(A) and j < len(B) :
            if A[i] > B[j]:
                list[k] = B[j]
                k = k + 1
                j = j + 1
            else:
                list[k] = A[i]
                k = k + 1
                i = i + 1
        while i < len(A):
            list[k] = A[i]
            k = k + 1
            i = i + 1
        while j < len(B):
            list[k] = B[j]
            k = k + 1
            j = j + 1
        return list

Last updated

Was this helpful?