|
| 1 | +const assert = require('assert'); |
| 2 | + |
| 3 | +/** |
| 4 | + * @param {number[]} nums1 |
| 5 | + * @param {number} m |
| 6 | + * @param {number[]} nums2 |
| 7 | + * @param {number} n |
| 8 | + * @return {void} Do not return anything, modify nums1 in-place instead. |
| 9 | + */ |
| 10 | +var merge = function (nums1, m, nums2, n) { |
| 11 | + // nums1 = [a, b, c, 0, 0, 0] |
| 12 | + // nums2 = [d, e, f] |
| 13 | + // Three pointers: |
| 14 | + // r1 (reader) = right of the relevant part of the first array (3) |
| 15 | + // r2 (reader) = right of the second array (3) |
| 16 | + // w (writter) = it will write at the end of the first array (5) |
| 17 | + let r1 = m - 1; |
| 18 | + let r2 = n - 1; |
| 19 | + |
| 20 | + for (let w = m + n - 1; w >= 0; w--) { |
| 21 | + if (r1 >= 0 && r2 >= 0) { |
| 22 | + nums1[w] = nums1[r1] > nums2[r2] ? nums1[r1--] : nums2[r2--]; |
| 23 | + } else if (r1 >= 0) { |
| 24 | + nums1[w] = nums1[r1--]; |
| 25 | + } else if (r2 >= 0) { |
| 26 | + nums1[w] = nums2[r2--]; |
| 27 | + } |
| 28 | + } |
| 29 | +}; |
| 30 | + |
| 31 | +function test(tt) { |
| 32 | + tt.forEach(t => { |
| 33 | + merge(t.nums1, t.m, t.nums2, t.n); |
| 34 | + assert.deepStrictEqual(t.nums1, t.expected); |
| 35 | + }); |
| 36 | +} |
| 37 | + |
| 38 | +const tt = [ |
| 39 | + { |
| 40 | + nums1: [1, 2, 3, 0, 0, 0], |
| 41 | + m: 3, |
| 42 | + nums2: [2, 5, 6], |
| 43 | + n: 3, |
| 44 | + expected: [1, 2, 2, 3, 5, 6], |
| 45 | + }, |
| 46 | + { |
| 47 | + nums1: [1], |
| 48 | + m: 1, |
| 49 | + nums2: [], |
| 50 | + n: 0, |
| 51 | + expected: [1], |
| 52 | + }, |
| 53 | + { |
| 54 | + nums1: [0], |
| 55 | + m: 0, |
| 56 | + nums2: [1], |
| 57 | + n: 1, |
| 58 | + expected: [1], |
| 59 | + }, |
| 60 | +] |
| 61 | + |
| 62 | +test(tt); |
0 commit comments