88. Merge Sorted Array

μ •λ ¬λ˜μ§€ μ•Šμ€ 두 개의 μ •μˆ˜ λ°°μ—΄ nums1, nums2 이 주어지고
각 λ°°μ—΄μ˜ μš”μ†Œ 수λ₯Ό λ‚˜νƒ€λ‚΄λŠ” 두 μ •μˆ˜ m, n 이 μ£Όμ–΄μ§ˆ 것이닀.

nums1 κ³Ό nums2 λ₯Ό λ‚΄λ¦Όμ°¨μˆœμœΌλ‘œ μ •λ ¬λœ 단일 λ°°μ—΄λ‘œ λ³‘ν•©ν•˜λ„λ‘ μž‘μ„±ν•˜λΌ.

μ΅œμ’…μ μœΌλ‘œ μ •λ ¬λœ 배열은 ν•¨μˆ˜μ— μ˜ν•΄ λ°˜ν™˜λ˜λŠ” 것이 μ•„λ‹ˆλΌ nums1 에 μ €μž₯λ˜μ–΄μ•Ό ν•œλ‹€.

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
    -10^9 <= nums1[i], nums2[j] <= 10^9

Solution

class Solution {
    func merge(_ nums1: inout [Int], _ m: Int, _ nums2: [Int], _ n: Int) {
        var res: [Int] = [Int]()
        
        if m > 0 {
            for i in 0..<m {
            res.append(nums1[i])
            }
        }
        
        if n > 0 {
            for i in 0..<n {
            res.append(nums2[i])
            }
        }
        
        nums1 = res.sorted(by: <)
    }
}

nums1 을 m 만큼 nums2 λ₯Ό n 만큼 res 배열에 λ„£κ³ 
μ˜€λ¦„μ°¨μˆœμœΌλ‘œ μ •λ ¬ν•˜λ„λ‘ κ΅¬ν˜„ν•˜μ˜€λ‹€.

nums1 을 inout 으둜 mutable ν•˜κ²Œ μ€€ 뢀뢄을 잘 ν™œμš©ν•˜λ©΄ 쒋을 것 κ°™λ‹€..πŸ˜…


πŸ“š Reference
LeetCode-88-MergeSortedArray