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.
Java:
自己模仿写一下:
http://blog.youkuaiyun.com/linhuanmars/article/details/19712333
public class Solution {
public void merge(int A[], int m, int B[], int n) {
int k=m+n-1;
int i=m-1;
int j=n-1;
while(i>=0&&j>=0)
{
if(A[i]>=B[j])
{
A[k]=A[i];
k--;
i--;
}
else
{
A[k]=B[j];
k--;
j--;
}
}
while(j>=0){
A[k]=B[j];
j--;
k--;
}
}
}
Reference:
1.http://blog.youkuaiyun.com/lilong_dream/article/details/22677537
public class Solution {
public void merge(int A[], int m, int B[], int n) {
int idx = m + n - 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--];
}
}
if (i == -1) {
while (j >= 0) {
A[j] = B[j];
j--;
}
}
}
}
2.http://gongxuns.blogspot.com/2012/12/leetcode-merge-sorted-array.html
public class Solution {
public void merge(int A[], int m, int B[], int n) {
// Start typing your Java solution below
// DO NOT write main() function
int i = m-1,
j = n-1,
k = m+n-1;
while(k>=0){
if(j<0 || (i>=0 && A[i]>B[j]))
A[k--]=A[i--];
else
A[k--]=B[j--];
}
}
}