개발일지

88. Merge Sorted Array 본문

Algorithm

88. Merge Sorted Array

wa_n 2023. 8. 24. 13:33
728x90
반응형

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 및 nums2의 요소 수를 나타내는 두 개의 정수 m 및 n이 제공됩니다. nums1과 nums2를 비내림차순으로 정렬된 단일 배열로 병합합니다. 최종 정렬된 배열은 함수에 의해 반환되지 않고 대신 배열 nums1 내에 저장되어야 합니다. 이를 수용하기 위해 nums1의 길이는 m + n입니다. 여기서 처음 m개 요소는 병합해야 하는 요소를 나타내고 마지막 n개 요소는 0으로 설정되어 무시되어야 합니다. nums2의 길이는 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

문제를 보면 nums1에 nums2가 병합되면서 정렬된 형태로 나오면 될 거 같다. 0을 제거하고 그 안에 값을 넣어서 병합 후 정렬을 하는 식으로 접근해 보자

nums1.length == m + n 이므로 nums2의 값들을 nums1에 넣어주어야 하니까 for문을 nums2만큼 반복해서 그 값들을 nums1에 병합해 주면 될 거 같다.

for문으로 nums1에 nums2를 넣어서 병합하는 것이기 때문에 nums2를 기준으로 반복하여 값을 찾아준다

for(let i = 0; i < n; i++)

nums1 [m+i] 자리에 nums2 [i] 값을 넣어준다.

nums1[m+i]=nums2[i]

넣어준 후 sort로 배열을 정렬해 준다.

return nums1.sort((a,b)=> a-b)
var merge = function(nums1, m, nums2, n) {
   
    for(let i =0; i <n; i++ ){
       nums1[m+i]=nums2[i]
    }
  return nums1.sort((a,b)=> a-b)
};
728x90
반응형

'Algorithm' 카테고리의 다른 글

27. Remove Element  (0) 2023.08.24
컨트롤 제트 .py  (0) 2023.08.10
최솟값 만들기  (0) 2023.05.17
로또의 최고 순위와 최저 순위  (0) 2023.04.03
문자열 내 마음대로 정렬하기  (0) 2023.04.03