Merge Sorted Array

박정현·2022년 3월 2일
0

LeetCode

목록 보기
8/18
post-thumbnail

📚문제

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.

Constraints:

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

❗️첫번째 시도

var merge = function(nums1, m, nums2, n) {
   nums1.splice(m)   // [1,2,3]
   nums2.splice(n)   // [2,5,6]
     
   nums1 = nums2.concat(nums1).sort((a, b) => a - b)
   
};

❗️ 이상한 건 이 코드를 찍고 콘솔에 nums1을 찍으면 정답인 [1,2,2,3,5,6] 가 나온다는 것이었다..
계속 찍고 연구를 해본 결과 이 문제는 nums1을 재선언 또는 재할당 하면 안되는 문제였다.
내가 작성한 코드는 concat이라는 과정을 하면서 nums1을 재할당 했기 때문에
splice 단계에서 변형한 [1, 2, 3]만 계속 리턴되는 것이었다😳

💡풀이

var merge = function (nums1, m, nums2, n) {
    // nums1에서 m만큼 자르고 그 뒤에 n만큼 nums2를 붙인다
    // 그리고 오름차순 정렬을 해준다

    nums1.splice(m, n, ...nums2);
    nums1.sort((a, b) => a - b);
};

✅ arr.splice(): 배열의 기존 요소를 삭제 또는 교체하거나 새 요소를 추가하여 배열의 내용을 변경

이렇게 또 한번 배우고 splice를 적용하는 과정에 대해서 배우는 계기가 되었다!

profile
공부하고 비행하다 개발하며 여행하는 frontend engineer

0개의 댓글