일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
- 순열
- 전화영어
- 회사폐업
- 취업사실신고
- 네트워크
- 막대기자르기
- 사회초년생
- 알고리즘
- 정보처리기사개정
- 실업인정인터넷신청
- leetcode
- 자취준비
- 튜터링
- 코딩테스트
- C++
- 후니의쉽게쓴시스코네트워킹
- 청년내일채움공제
- IT기초
- 실업급여
- 동적계획법
- 캡쳐링
- 생애첫계약
- 프로그래머스
- array
- 후니의쉽게쓴시스코라우팅
- 자료구조
- 부분합알고리즘
- 모여봐요동물의숲
- 정보
- HeadFirstDesignPatterns
- Today
- Total
따봉도치야 고마워
[LeetCode] Arrays 101: Merge Sorted Array 본문
문제
오름차순으로 정렬된 두 개의 정수 배열 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);
};
//둘 다 정렬되어 있으니까, 비교해서 넣어도 될 것 같음
'프로그래밍 > 알고리즘' 카테고리의 다른 글
[LeetCode] Arrays 101: Remove Duplicates from Sorted Array (0) | 2022.04.07 |
---|---|
[LeetCode] Arrays 101: Remove Element (0) | 2022.04.07 |
[LeetCode] Arrays 101: Duplicate Zeros (0) | 2022.04.07 |
[LeetCode] Arrays 101: Squares of a Sorted Array (0) | 2022.04.05 |
[LeetCode] Arrays 101: Find Numbers with Even Number of Digits (0) | 2022.04.05 |