作者:disappearedgod
时间:2014-4-23
题目
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 (size that is greater or equal to m + n) to hold additional elements from B. The number of elements initialized in A and B are m andn respectively.
解法
思想
将B数组的值归并到A数组中,就是比较末尾然后放入
代码中用了个小技巧,因为不知道是对i递减还是对j递减,所以先递减然后在后面补充回来。
如果B数组中的值比对完即可,不用等A中值比对完再截止。
public class Solution {
public void merge(int A[], int m, int B[], int n) {
if(n==0)
return;
int i = m-1;
int j = n-1;
int bigger = 0;
while(j>=0 && i>=0){
if(A[i]>B[j])
bigger = A[i--];
else
bigger = B[j--];
A[i+j+1+1]=bigger;//bigger = A/B[i/j--] the last 1 make up "--"
}
while(j>=0){
A[j]=B[j];
j--;
}
}
}