题解 | #合并两个有序的数组#
合并两个有序的数组
http://www.nowcoder.com/practice/89865d4375634fc484f3a24b7fe65665
从前往后进行遍历
需要开辟空间
import java.util.*;
public class Solution {
public void merge(int A[], int m, int B[], int n) {
int tmp[] = new int[n + m];
int i = 0,j = 0;
int idx = 0;
while(i < m && j < n){
if(A[i] <= B[j]){
tmp[idx++] = A[i++];
}else {
tmp[idx++] = B[j++];
}
}
while(i < m){tmp[idx++] = A[i++];}
while(j < n){tmp[idx++] = B[j++];}
for(i = 0;i < n + m;i++){
A[i] = tmp[i];
}
}
}
从后往前进行遍历
不需要开辟空间
import java.util.*;
public class Solution {
public void merge(int A[], int m, int B[], int n) {
int idx = n + m - 1;
int i = m - 1;
int j = n - 1;
while(i >= 0 && j >= 0){
if(A[i] >= B[j])A[idx--] = A[i--];
else {
A[idx--] = B[j--];
}
}
while(i >= 0)A[idx--] = A[i--];
while(j >= 0)A[idx--] = B[j--];
}
}