LintCode之合併排序數組II

題目描述:數組

分析:題目的意思是把數組A和數組B合併到數組A中,且數組A有足夠的空間容納A和B的元素,合併後的數組依然是有序的。spa

個人代碼:code

 1 public class Solution {
 2     /*
 3      * @param A: sorted integer array A which has m elements, but size of A is m+n
 4      * @param m: An integer
 5      * @param B: sorted integer array B which has n elements
 6      * @param n: An integer
 7      * @return: nothing
 8      */
 9     public void mergeSortedArray(int[] A, int m, int[] B, int n) {
10         // write your code here
11         //建立數組c
12         int[] c = new int[m+n];
13         int i=0,j=0,k=0;
14         
15         while(i<m && j<n) {
16             if(A[i] <= B[j]) {
17                 c[k++] = A[i];
18                 i++;
19             }else {
20                 c[k++] = B[j];
21                 j++;
22             }
23         }
24         while(i < m) {
25             c[k++] = A[i];
26             i++;
27         }
28         while(j < n) {
29             c[k++] = B[j];
30             j++;
31         }
32         
33         //將數組c中的值賦給A
34          for(int r=0; r<c.length; r++) {
35             A[r] = c[r];
36         }
37     }
38 }
相關文章
相關標籤/搜索