따봉도치야 고마워

[LeetCode] Arrays 101: Merge Sorted Array 본문

프로그래밍/알고리즘

[LeetCode] Arrays 101: Merge Sorted Array

따봉도치 2022. 4. 7. 18:04

문제

오름차순으로 정렬된 두 개의 정수 배열 nums1, nums2와 각 배열의 사이즈를 의미하는 m, n 을 입력받는다.

nums1과 nums2를 하나의 오름차순 배열로 합쳐라.

 

새로운 값으로 반환하지 않고, nums1에 합친다.

최종적으로 nums1은 m+n 의 요소를 가져야 하며, 처음에 제공되는 nums1에서 끝에서 n만큼의 요소는 0으로 세팅 된다.

 

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

 

Follow up: Can you come up with an algorithm that runs in O(m + n) time?

 


Code

var merge = function(nums1, m, nums2, n) {
    if (n === 0) return;
    
    for (let i = m; i < m + n; i++) {
        nums1[i] = nums2[i - m];
    }
    
    nums1.sort((a, b) => a - b);
};

//둘 다 정렬되어 있으니까, 비교해서 넣어도 될 것 같음
Comments