leetcode Question 53: Merge Sorted Array

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 to hold additional elements from B. The number of elements initialized in A and B are m and n respectively.

Analysis:
The classic problem. (can be found in the book "Cracking the Code Interview").
Part of the merge sort, merge the arrays from the back by comparing the elements.

Code(Updated 201309):

class Solution {
public:
    void merge(int A[], int m, int B[], int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int count=m+n-1;
        m--; n--;
        while (m>=0 && n>=0){
            A[count--] = A[m]>B[n]? A[m--]:B[n--];
        }
        while (n>=0){ A[count--] = B[n--];}
    }
};

Code(Old version):

class Solution {
public:
    void merge(int A[], int m, int B[], int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int k=m+n-1;
        int i=m-1;
        int j=n-1; 
        while (i>=0 && j>=0){
            if (A[i]>B[j]){
                A[k--]=A[i--];
            }else{
                A[k--]=B[j--];
            }
        }
        while (j>=0){
            A[k--]=B[j--];
        }
        return;
    }
};

5 comments:

  1. Why is the while (m>=0) condition not handled ? How come the smallest elements always are in B ?

    ReplyDelete
    Replies
    1. Because the remaining elements are already in the array A

      Delete
  2. This comment has been removed by the author.

    ReplyDelete
  3. How about this?

    void merge(vector& nums1, int m, vector& nums2, int n) {

    if(n == 0 || (n==0 && m==0))
    return;

    nums1.erase(nums1.begin()+m, nums1.end());

    for(int i=0; i<n; i++)
    nums1.push_back(nums2[i]);

    sort(nums1.begin(), nums1.end());

    }

    ReplyDelete