题目描述:
分析:题目的意思是把数组A和数组B合并到数组A中,且数组A有足够的空间容纳A和B的元素,合并后的数组依然是有序的。
我的代码:
public class Solution {
/*
* @param A: sorted integer array A which has m elements, but size of A is m+n
* @param m: An integer
* @param B: sorted integer array B which has n elements
* @param n: An integer
* @return: nothing
*/
public void mergeSortedArray(int[] A, int m, int[] B, int n) {
// write your code here
//创建数组c
int[] c = new int[m+n];
int i=0,j=0,k=0; while(i<m && j<n) {
if(A[i] <= B[j]) {
c[k++] = A[i];
i++;
}else {
c[k++] = B[j];
j++;
}
}
while(i < m) {
c[k++] = A[i];
i++;
}
while(j < n) {
c[k++] = B[j];
j++;
} //将数组c中的值赋给A
for(int r=0; r<c.length; r++) {
A[r] = c[r];
}
}
}