Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

《程序员面试金典(第 6 版)》10.01. 合并排序的数组 #81

Open
Tcdian opened this issue Mar 24, 2020 · 1 comment
Open
Labels

Comments

@Tcdian
Copy link
Owner

Tcdian commented Mar 24, 2020

《程序员面试金典(第 6 版)》10.01. 合并排序的数组

给定两个排序后的数组 A 和 B,其中 A 的末端有足够的缓冲空间容纳 B。 编写一个方法,将 B 合并入 A 并排序。

初始化 A 和 B 的元素数量分别为 m 和 n。

Example 1

输入:
A = [1,2,3,0,0,0], m = 3
B = [2,5,6],       n = 3

输出: [1,2,2,3,5,6]

Note

  • A.length == n + m
@Tcdian
Copy link
Owner Author

Tcdian commented Mar 24, 2020

Solution

  • JavaScript Solution
/**
 * @param {number[]} A
 * @param {number} m
 * @param {number[]} B
 * @param {number} n
 * @return {void} Do not return anything, modify A in-place instead.
 */
var merge = function(A, m, B, n) {
    let i = m + n - 1;
    let AI = m - 1;
    let BI = n - 1;

    while (BI >= 0) {
        if ( AI >= 0 && A[AI] > B[BI]) {
            swap(A, AI, i);
            AI--;
        } else {
            A[i] = B[BI];
            BI--;
        }
        i--;
    }

    function swap(arr, a, b) {
        const temp = arr[a];
        arr[a] = arr[b];
        arr[b] = temp;
    }
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant