【LeetCode】- Merge Sorted Array (合并有序数组).

时间:2022-10-01 04:14:52

问题: ]

Given two sorted integer arrays A and B, merge B into A as one sorted array.

直译:给定两个排好序的整形数组,将数组B合并到数组A,形成一个新的数组。


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 and n respectively.


[ 解法]

题解:从结尾开始归并,不会覆盖元素又能满足题意。
参数m:数组m位置后面元素会被数组B中元素替换
参数n:从第一个开始,将数组B中n个元素会被合并到数组A

public class Solution {
	public static void main(String[] args) {
		int[] A = { 1, 2, 4, 5, 6, 8 };
		int[] B = { 3, 9, 10 };
		new Solution().merge(A, 3, B, 2);  // 1 2 3 4 9 8
	}

	public void merge(int A[], int m, int B[], int n) {
		int i, j, k;
		for (i = m - 1, j = n - 1, k = m + n - 1; k >= 0; --k) {
			if (i >= 0 && (j < 0 || A[i] > B[j])) {
				A[k] = A[i--];
			} else {
				A[k] = B[j--];
			}
		}
	}
}