Merge Sorted Array
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