
Description
Easy
Topics
Companies
Hint
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
package main
import (
"fmt"
)
func main() {
merge([]int{1, 2, 3, 0, 0, 0}, 3, []int{2, 5, 6}, 3)
}
func merge(nums1 []int, m int, nums2 []int, n int) {
// m == 0
if m == 0 {
copy(nums1, nums2)
}
// n == 0
if n == 0 {
return
}
// m != 0 && n != 0
merged := make([]int, m+n)
k, i, j := 0, 0, 0
for i < m && j < n {
if nums1[i] < nums2[j] {
merged[k] = nums1[i]
i++
} else {
merged[k] = nums2[j]
j++
}
k++
}
for i < m {
merged[k] = nums1[i]
i++
k++
}
for j < n {
merged[k] = nums2[j]
j++
k++
}
copy(nums1, merged)
fmt.Println(nums1)
}
merge 함수는 두 개의 정렬된 배열 nums1과 nums2를 병합하여 하나의 정렬된 배열로 만드는 함수
구현 방식
- nums1은 m + n 크기를 가지며, 앞쪽 m개의 원소는 정렬된 상태이고 뒤쪽 n개의 원소는 0으로 비어 있습니다.
- nums2는 n개의 정렬된 원소를 포함합니다.
- nums1과 nums2를 비교하면서 새로운 배열 merged에 작은 값을 먼저 삽입하고, 남은 요소도 추가합니다.
- 마지막으로 merged 배열을 nums1에 복사하여 병합을 완료
'leetcode , 백준' 카테고리의 다른 글
94. Binary Tree Inorder Traversal (0) | 2025.03.19 |
---|---|
[DFS-중위 순회] LeetCode 94번 문제 학습 (0) | 2025.03.19 |
[Go] 2869 달팽이는 올라가고 싶다 (0) | 2025.01.13 |
[Go] 2346 풍선 터뜨리기 (0) | 2025.01.08 |
[Go] 28279 덱 2 (0) | 2025.01.07 |