Skip to content

Latest commit

 

History

History
72 lines (46 loc) · 1.19 KB

README_EN.md

File metadata and controls

72 lines (46 loc) · 1.19 KB

中文文档

Description

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]

Solutions

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--;
        }
    }
};

...