merge-sorted-array——合并两个有序数组

时间:2022-11-17 04:13:36

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.

 

归并排序

 1 class Solution {
 2 public:
 3     void merge(int A[], int m, int B[], int n) {
 4         vector<int> v(m+n,0);
 5         int i=0,j=0,k=0;
 6         while(i<m&&j<n){
 7             if(A[i]<B[j])
 8                 v[k++]=A[i++];
 9             else
10                 v[k++]=B[j++];
11             
12         }
13         while(i<m){
14             v[k++]=A[i++];
15             
16         }
17         while(j<n){
18             v[k++]=B[j++];
19         }
20         for(i=0;i<m+n;i++)
21             A[i]=v[i];
22     }
23 };