You are given two sorted arrays, A and B, where A has a large enough buffer at the end to hold B. Write a method to merge B into A in sorted order.
Initially the number of elements in A and B are m and n respectively.
Example:
Input: A = [1,2,3,0,0,0], m = 3 B = [2,5,6], n = 3
Output: [1,2,2,3,5,6]
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/sorted-merge-lcci 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
A的后面是空的,所以可以换一个思路,从最后一个值开始判断最大值存入
从后往前遍历,就不会被内存空间所限制
class Solution {
public void merge(int[] A, int m, int[] B, int n) {
int a=m-1;
int b=n-1;
for(int i=m+n-1;i>=0;i--){
if(b<0||(a>=0&&A[a]>B[b])){
A[i]=A[a];
a--;
}else{
A[i]=B[b];
b--;
}
}
}
}