Wednesday, May 21, 2014

LeetCode: Merge Sorted Array

Given two sorted integer arrays A and B, merge B into A as one sorted array.

Note:
You may assume that A has enough space (size that is greater or equal to m + n) to hold additional elements from B. The number of elements initialized in A and B are m and n respectively.


We can start from the end of the new array and begin merging from end to the front.

C++ Code:

/*
 * func: merge_sorted_array
 * goal: merge sorted array B into A
 * @param A: sorted array A
 * @param m: the size of array A
 * @param B: sorted array B
 * @param n: the size of array B
 * return:
 */
/*
 * we can start from the end and backwards
 * complexity: time O(n+m), space O(1)
 */
void merge_sorted_array(int A[], int m, int B[], int n){
    int k = m + n - 1;
    while(m > 0 && n > 0){
        if(A[m-1] >= B[n-1]){
            A[k] = A[m-1];
            --k;
            --m;
        }else{
            A[k] = B[n-1];
            --k;
            --n;
        }
    }
    while(n > 0){
        A[k] = B[n-1];
        --n;
        --k;
    }
}

Python Code:

# func: merge two sorted array
# @param A: input list A
# @param m: length of A
# @param B: input list B
# @param n: length of B
# @return:
# complexity: time O(m+n), space O(1)
def merge_sorted_array(A, m, B, n):
    k = m + n - 1
    while m > 0 and n > 0:
        if A[m-1] >= B[n-1]:
            A[k] = A[m-1]
            m -= 1
            k -= 1
        else:
            A[k] = B[n-1]
            n -= 1
            k -= 1
    while n > 0:
        A[k] = B[n-1]
        k -= 1
        n -= 1

No comments:

Post a Comment