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]

Challenge

How can you optimize your algorithm if one array is very large and the other is very small?

两两比较就行。Challenge里想说让做binary search。但是binary search也没用。因为要挪数组元素,不可能比O(N+M)快

    def mergeSortedArray(self, A, B):
        i = j = 0
        result = []
        while i < len(A) and j < len(B):
            if A[i] < B[j]:
                result.append(A[i])
                i += 1
            else:
                result.append(B[j])
                j += 1

        while i < len(A):
            result.append(A[i])
            i += 1

        while j < len(B):
            result.append(B[j])
            j += 1

        return result

Last updated

Was this helpful?