본문 바로가기
LeetCode/코딩 테스트 스터디 3주차

[LeetCode] 88. Merge Sorted Array 풀이 (JS)

by inwoo1324 2022. 7. 24.

0. 문제

https://leetcode.com/problems/merge-sorted-array/

 

Merge Sorted Array - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

정렬된 두개의 배열을 합쳐서 하나의 정렬된 배열을 만드는 문제

#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.

#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:

#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.

1.언어

자바스크립트(JavaScript)

 

2. 문제 풀이

var merge = function(nums1, m, nums2, n) {
    nums1.sort((x,y) => x-y);
    let zeroInd = nums1.indexOf(0);
    for (let i = zeroInd; i < zeroInd+n; i++) nums1[i] = nums2[i-zeroInd];
    nums1.sort((x,y) => x-y);
};
Runtime: 65 ms, faster than 90.29% of JavaScript online submissions for Merge Sorted Array.
Memory Usage: 42.2 MB, less than 38.68% of JavaScript online submissions for Merge Sorted Array.

 

1. 입력값 num1을 오름차순 정렬로 0을 한 흐름으로 모은다.

2. 0의 위치를 찾고 num2를 입력값 n만큼 반복문으로 값을 할당한다.

3. 오름차순으로 정렬한다.