64. 合并排序数组 II

描述

合并两个排序的整数数组A和B变成一个新的数组。

注意事项

你可以假设A具有足够的空间(A数组的大小大于或等于m+n)去添加B中的元素。

样例

给出 A = [1, 2, 3, empty, empty], B = [4, 5]
合并之后 A 将变成 [1,2,3,4,5]

思路

这个题型时间复杂度能不能最优是要根据给的数组来判断,若空位在前面从头遍历两个数组,若空位在后面从后面开始遍历两个数组

代码

public class Solution {
    /*
     * @param A: sorted integer array A which has m elements, but size of A is m+n
     * @param m: An integer
     * @param B: sorted integer array B which has n elements
     * @param n: An integer
     * @return: nothing
     */
    public void mergeSortedArray(int[] A, int m, int[] B, int n) {
        int i = m - 1;
        int j = n - 1;
        int index = m + n - 1;
        while (i >= 0 && j >= 0) {
            if (A[i] > B[j]) {
                A[index--] = A[i--];
            } else {
                A[index--] = B[j--];
            }
        }
        // 较长数组A遍历完了,较短数组B还没遍历完
        // 链表这个地方可以用if,直接把指针连接就可以了,但数组要用while来循环来一一复制每个元素
        while (j >= 0) {
            A[index--] = B[j--];
        }
        // 往较长数组A合并,若把较短数组B遍历完了则较长数组A剩余的部分不用管,仍旧在原数组中
    }
}

你可能感兴趣的:(64. 合并排序数组 II)