[Javascript] leetcode 88. Merge Sorted Array

준이·2025년 7월 2일

leetcode

목록 보기
1/3

Array / String - 88. Merge Sorted Array

정렬된 두 배열 nums1, nums2가 주어짐

nums1은 길이가 m + n이고,
앞쪽 m개만 유효한 값, 뒤쪽 n개는 0으로 채워져 있음

nums2는 길이 n, 전부 유효한 값

이 두 배열을 하나로 병합하고,
nums1 내부에 정렬된 상태로 저장해야 함 (in-place)

예제

Example 1:

Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
Output: [1,2,2,3,5,6]
Explanation: The arrays we are merging are [1,2,3] and [2,5,6].
The result of the merge is [1,2,2,3,5,6] with the underlined elements coming from nums1.

Example 2:

Input: nums1 = [1], m = 1, nums2 = [], n = 0
Output: [1]
Explanation: The arrays we are merging are [1] and [].
The result of the merge is [1].

Example 3:

Input: nums1 = [0], m = 0, nums2 = [1], n = 1
Output: [1]
Explanation: The arrays we are merging are [] and [1].
The result of the merge is [1].
Note that because m = 0, there are no elements in nums1. The 0 is only there to ensure the merge result can fit in nums1.

풀이

/**
 * @param {number[]} nums1
 * @param {number} m
 * @param {number[]} nums2
 * @param {number} n
 * @return {void} Do not return anything, modify nums1 in-place instead.
 */
var merge = function(nums1, m, nums2, n) {

  // ① 0 패딩을 제외한 앞 m개 + nums2 를 합친 새 배열
  const merged = [...nums1.slice(0, m), ...nums2];

  // ② 오름차순 정렬
  merged.sort((a, b) => a - b);

    // ③ 결과를 nums1 에 되돌려 넣기 (in-place)
  for (let i = 0; i < m + n; i++) {
    nums1[i] = merged[i];
  }

};

알아야 될 개념

slice() : 어떤 배열의 begin 부터 end 까지(end 미포함)에 대한 얕은 복사본을 새로운 배열 객체로 반환합니다. 원본 배열은 바뀌지 않습니다.

> nums = Array(20).fill().map((_, i) => i)
< [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

> nums.slice(5, 10)
< [5, 6, 7, 8, 9]

> nums.slice(10)
< [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

오름차순 : 작은 수부터 큰 수로 정렬.

merged.sort((a, b) => a - b);
profile
25% Speciallist

0개의 댓글