LintCode之合并排序数组II

题目描述:

分析:题目的意思是把数组A和数组B合并到数组A中,且数组A有足够的空间容纳A和B的元素,合并后的数组依然是有序的。

我的代码:

 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 }

 

posted @ 2017-11-09 20:21  zwt3  阅读(303)  评论(0编辑  收藏  举报