넘치게 채우기

[LeetCode] 88. Merge Sorted Array 본문

PS/LeetCode

[LeetCode] 88. Merge Sorted Array

riveroverflow 2023. 6. 30. 13:55
728x90
반응형

https://leetcode.com/problems/merge-sorted-array/description/?envType=study-plan-v2&envId=top-interview-150 

 

Merge Sorted Array - LeetCode

Can you solve this real interview question? Merge Sorted Array - 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 an

leetcode.com

문제 유형 : 배열 / 정렬

문제 난이도 : Easy

 

문제

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.

 

nums1과 nums2 감소하지 않는 순서의 정수형 배열이 있다. 

nums1의 길이는 m+n, nums2의 길이는 n이다. nums1에는 m개의 값이 있고, '0'으로 설정된 값이 배열 뒤쪽에 n개 있다.

nums1의 빈공간에 nums2를 넣고, 감소하지 않는 순서로 만드시오.

 

 

풀이

nums1의 m번째 인덱스부터 nums2의 0번째 인덱스에 있는 값을 순차적으로 인덱스를 늘려주면서 값을 넣어주는 과정을 N번 반복하면 된다.

(예시 : nums1 - [1,2,3,0,0,0], nums2 - [2,5,6]인 경우, 0,0,0에 2,5,6을 넣어주면 된다.)

그 뒤, nums1을 정렬해주면 끝,

 

코드(C++)

class Solution {
public:
    void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
        for(int i = m; i < m+n; i++){
            nums1[i] = nums2[i-m];
        }

        sort(nums1.begin(), nums1.end());
    }
};
 
728x90
반응형

'PS > LeetCode' 카테고리의 다른 글

[LeetCode] 26. Remove Duplicates from Sorted Array  (0) 2023.07.02
[LeetCode] 27. Remove Element  (0) 2023.07.01
[LeetCode] 20. Valid Parentheses  (0) 2023.06.29
[LeetCode] 392. Is Subsequence  (0) 2023.06.28
[LeetCode] 58. Length of Last Word  (0) 2023.06.27