//我自己的版本
public class Solution {
public void merge(int A[], int m, int B[], int n) {
int a =m-1;
int b=n-1;
while(a!=-1||b!=-1){
if(b==-1)//A中剩余的加进来
{
A[a+b+1]=A[a];
a--;
continue;
}
if(a==-1){//B中剩余的加进来
A[a+b+1]=B[b];
b--;
continue;
}
if(A[a]>B[b]){
A[a+b+1]=A[a];
a--;
}else{
A[a+b+1]=B[b];
b--;
}
}
}
}
方法一:直接合并后排序
算法
最直观的方法是先将数组 BB 放进数组 AA 的尾部,然后直接对整个数组进行排序
class Solution {
public void merge(int[] A, int m, int[] B, int n) {
for (int i = 0; i != n; ++i) {
A[m + i] = B[i];
}
Arrays.sort(A);
}
}
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/sorted-merge-lcci/solution/mian-shi-ti-1001-he-bing-
//双指针法我们为两个数组分别设置一个指针 pa 与 pb 来作为队列的头部指针。代码实现如下:
class Solution {
public void merge(int[] A, int m, int[] B, int n) {
int pa = 0, pb = 0;
int[] sorted = new int[m + n];
int cur;
while (pa < m || pb < n) {
if (pa == m) {
cur = B[pb++];
} else if (pb == n) {
cur = A[pa++];
} else if (A[pa] < B[pb]) {
cur = A[pa++];
} else {
cur = B[pb++];
}
sorted[pa + pb - 1] = cur;
}
for (int i = 0; i != m + n; ++i) {
A[i] = sorted[i];
}
}
}
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/sorted-merge-lcci/solution/mian-shi-ti-1001-he-bing-pai-xu-de-shu-zu-by-leetc/
//逆向双指针fa
class Solution {
public void merge(int[] A, int m, int[] B, int n) {
int pa = m - 1, pb = n - 1;
int tail = m + n - 1;
int cur;
while (pa >= 0 || pb >= 0) {
if (pa == -1) {
cur = B[pb--];
} else if (pb == -1) {
cur = A[pa--];
} else if (A[pa] > B[pb]) {
cur = A[pa--];
} else {
cur = B[pb--];
}
A[tail--] = cur;
}
}
}
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/sorted-merge-lcci/solution/mian-shi-ti-1001-he-bing-pai-xu-de-shu-zu-by-leetc/