Algorithm

[LeetCode] Merge Sorted Array

죠죠_ 2023. 9. 11. 16:20

문제 

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.

 

주어진 배열 nums1nums2는 순서대로 정렬되어있으며, Integer mn은 각각 nums1nums2가 가진 element의 수를 의미한다. 

 

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

nums1nums2를 합치고 오름차순으로 정렬하라.

 

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.

 

nums1의 길이는 m + n이며, nums1[m]부터 n까지는 0으로 이루어져있어 이를 무시하고 길이가 n인 nums2nums1에 병합해야한다

풀이 

var merge = function(nums1, m, nums2, n) {
    nums1.splice(m, n);
    nums1.push(...nums2);
    nums1.sort((a, b) => a - b);
};

Runtime: 49 ms

Memory Usage: 42.3 MB