Question:
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 to hold additional elements from B. The number of elements initialized in A and B are m and n respectively.
public class Solution {
public void merge(int A[], int m, int B[], int n) {
int pointerA = m - 1;
int pointerB = n - 1;
int p = m + n - 1;
while (pointerA >= 0 && pointerB >= 0) {
if (A[pointerA] > B[pointerB]) {
A[p] = A[pointerA];
pointerA--;
} else {
A[p] = B[pointerB];
pointerB--;
}
p--;
}
while (pointerA >= 0) {
A[p] = A[pointerA];
pointerA--;
p--;
}
while (pointerB >= 0) {
A[p] = B[pointerB];
pointerB--;
p--;
}
}
}
本文介绍了一种将两个已排序的整数数组A和B合并为一个排序数组A的算法实现。该算法采用双指针法从后向前比较并合并两个数组,确保了合并后的数组仍保持有序状态。
326

被折叠的 条评论
为什么被折叠?



