首页 > 代码库 > LeetCode OJ - Merge Sorted Array

LeetCode OJ - Merge Sorted Array

原地归并。

下面是AC代码:

 1  public void merge(int A[], int m, int B[], int n) {
 2         
 3          int len = A.length;
 4          //first copy m elements of A to the end of A
 5          for(int i=m-1,j = len-1;i>=0;i--){
 6              A[j--] = A[i];
 7          }
 8          //merge the A and B
 9          int startA = len - m;
10          int startB = 0;
11          int i = 0;
12          while(startA<len || startB<n){
13              while(startA<len&& startB<n && A[startA]<=B[startB])
14              {
15                  A[i++] = A[startA];
16                  startA++;
17              }
18              while(startA<len && startB<n && B[startB]<A[startA]){
19                  A[i++] = B[startB];
20                  startB++;
21              }
22              while(startA == len && startB<n){
23                  A[i++] = B[startB++];
24              }
25              while(startB == n  && startA<len){
26                  A[i++] = A[startA++];
27              }
28          }
29      }

 

 1 /**
 2       * second method very nice . from the end to start
 3       * @param A
 4       * @param m
 5       * @param B
 6       * @param n
 7       */
 8      public void merge2(int A[], int m, int B[], int n){
 9          int i = m+n-1;
10          while(i>=0 &&( n>=0 || m>=0)){
11              A[i--] = m-1 < 0? B[(n--)-1]:
12                  n-1 < 0? A[(m--)-1] : A[m-1]>=B[n-1]? A[(m--)-1]:B[(n--)-1];
13          }
14      }