Skip to content

Latest commit

 

History

History
123 lines (93 loc) · 2.37 KB

README.md

File metadata and controls

123 lines (93 loc) · 2.37 KB

English Version

题目描述

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

初始化 A 和 B 的元素数量分别为 mn

示例:

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

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

说明:

  • A.length == n + m

解法

Python3

Java

JavaScript

/**
 * @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 - 1,
        j = n - 1;
    for (let k = A.length - 1; k >= 0; k--) {
        if (k == i) return;
        if (i < 0 || A[i] <= B[j]) {
            A[k] = B[j];
            j--;
        } else {
            A[k] = A[i];
            i--;
        }
    }
};

TypeScript

/**
 Do not return anything, modify A in-place instead.
 */
function merge(A: number[], m: number, B: number[], n: number): void {
    for (let i = n + m - 1; i >= 0; i--) {
        const x = A[m - 1] ?? -Infinity;
        const y = B[n - 1] ?? -Infinity;
        if (x > y) {
            A[i] = x;
            m--;
        } else {
            A[i] = y;
            n--;
        }
    }
}

Rust

impl Solution {
    pub fn merge(a: &mut Vec<i32>, m: i32, b: &mut Vec<i32>, n: i32) {
        let mut m = m as usize;
        let mut n = n as usize;
        for i in (0..n + m).rev() {
            let x = if m != 0 { a[m - 1] } else { i32::MIN };
            let y = if n != 0 { b[n - 1] } else { i32::MIN };
            if x > y {
                a[i] = x;
                m -= 1;
            } else {
                a[i] = y;
                n -= 1;
            }
        }
    }
}

...