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) {
// Start typing your Java solution below
// DO NOT write main() function
int k = m + n - 1, i = m - 1, j = n - 1;
while(i >= 0 && j >= 0){
if(A[i] > B[j])
A[k--] = A[i--];
else
A[k--] = B[j--];
}
while(j >= 0)
A[k--] = B[j--];
}
}

本文介绍了一种将两个已排序的整数数组B合并到数组A中的方法,并保持合并后数组A为有序状态。通过从两个数组的末尾开始比较并放置较大元素的方式,实现了高效的原地合并。
373

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



