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

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
        vector<int>aa;
        aa.resize(m+n);
        int i=0,j=0,k=0;
        while(i<m&&j<n){
            if(A[i]>B[j]){
                aa[k]=B[j];
                j++;
                k++;
            }
            else{
                aa[k]=A[i];
                i++;
                k++;
            }
        }
        while(i<m){
            aa[k]=A[i];
            i++;
            k++;
        }
        while(j<n){
            aa[k]=B[j];
            j++;
            k++;
        }
        for(int i=0;i<m+n;i++){
            A[i]=aa[i];
        }
    }
};

 

posted @ 2013-09-15 15:54  懒猫欣  阅读(140)  评论(0编辑  收藏  举报