Leetcode - Merge sorted array

Yuni·2023년 8월 22일


목록 보기


You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively.

Merge nums1 and nums2 into a single array sorted in non-decreasing order.

The final sorted array should not be returned by the function, but instead be stored inside the array nums1. To accommodate this, nums1 has a length of m + n, where the first m elements denote the elements that should be merged, and the last n elements are set to 0 and should be ignored. nums2 has a length of n.


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.



  • nums1.length == m + n
  • nums2.length == n
  • 0 <= m, n <= 200
  • 1 <= m + n <= 200
  • -109 <= nums1[i], nums2[j] <= 109



In the beginning, I was thinking to create a new array that has both nums1 array and nums2 array. But soon, I realised I can only return nums1 array in this case. Although, the length of array1 is m+n, the valid value(length) is going to be m and nums2 array length is always going to be n. So I decided to use splice and the startpoint is going to be m+i and the maximum number of i is going to be n-1. After merging arrays, the merged array has to be sorted and negative numbers must be also considered.

  1. In the for loop, nums2 array is merging nums1 array using splice.
  2. Since the range of elements of nums1, nums2 includes negative numbers, the sort method needs to include conditional statements if.


처음에는 새로운 배열을 생성해 nums1과 nums2를 넣어 새로운 배열 = nums1을 하려고 했었다. (무참히 실패)
merge가 중요한 포인트구나 깨닫고 splice를 이용해 푸는 방법을 고안했다.
다만, nums1의 길이가 m+n일지라도 유효한 원소만의 길이는 m이므로 m 다음의 숫자부터 nums2의 원소를 넣어주면 된다. 그러므로 splice 시작포인트는 m+i, 그리고 i가 될 수 있는 최대의 숫자는 n-1일 것이다.
그렇게 머지가 완료 되면 오름차순 정렬을 해주면 되는데, 음수 및 10이상의 양수가 포함되어 있으므로 if 조건문을 사용하여 각 상황에 맞게 리턴값을 다르게 줘 오름차순 정렬했다.


 * @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) {
    for(let i=0; i<n; i++){
        nums1.splice(m + i, 1, nums2[i]);

    nums1.sort((a, b) => {
		if(a > b) return 1;
        if(a < b) return -1;
        if(a === b) return 0;
Look at art, make art, show art and be art. So does as code.

0개의 댓글