Merge Sorted Array
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 mand n respectively.
解法一:
public class Solution { public void merge(int A[], int m, int B[], int n) { if(m==0){ for(int i=0;i<n;i++){ A[i] = B[i]; } return; } if(n==0) return; int[] C = new int[m+n];//new一个大小为m+n的数组 int a = 0,b = 0,c = 0;//三个下标 while(a<m&&b<n){ if(A[a]<B[b]){ C[c++] = A[a]; if(a==m-1){ while(b<n){ C[c++] = B[b++];//A数组遍历结束,将B数组剩下元素顺序复制到C数组 } break; } else{ a++; } } else{ C[c++] = B[b]; if(b==n-1){ while(a<m){ C[c++] = A[a++];//B数组遍历结束,将A数组剩下元素顺序复制到C数组 } break; } else{ b++; } } } int k = 0; while(k<m+n){ A[k] = C[k]; k++; } } }
解法二:从后往前考虑,将2个数组中较大的存放在m+n-i位置处,i初始为1;这样每个元素存放的位置就是其最终位置,代码如下:
public class Solution { public void merge(int A[], int m, int B[], int n) { int i = m+n-1; int a = m-1; int b = n-1; while(a>=0&&b>=0) { if(A[a]>B[b]) A[i--] = A[a--]; else A[i--] = B[b--]; } while(b>=0){ A[i--] = B[b--]; } } }