본문 바로가기
IT/LeetCode

[LeetCode] 88. Merge Sorted Array

by 강천구 2022. 11. 15.

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
반응형

이 문제는 주어진 숫자 배열 2개 중 각각 m, n 갯수만큼 각각 배열에서 뽑아서 sort하는 문제이다.

while문을 통해 첫번째 숫자열을 뒤에서 하나씩 pop을 해서 m만큼까지 줄인다.  

두번째 숫자열에서는 앞에서 n개 만큼 첫번째 배열에 추가한 후 마지막에 sort() 함수를 이용해 결과를 리턴한다.

 

class Solution:
   def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
       while True:
           if nums1.__len__() == m: break
           else:
               nums1.pop(len(nums1)-1)

       count = 0
       while True:
           if count == n: break
           nums1.append(nums2[0])
           nums2.pop(0)
           count += 1

       nums1.sort()

 

 

Github : https://github.com/kkkkang1009/leetcode/blob/master/leetcode_88.py

 

GitHub - kkkkang1009/leetcode: leetcode

leetcode. Contribute to kkkkang1009/leetcode development by creating an account on GitHub.

github.com

 

문제 출처 : https://leetcode.com/problems/merge-sorted-array/

 

Merge Sorted Array - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

반응형

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

[LeetCode] 96. Unique Binary Search Trees  (0) 2023.01.15
[LeetCode] 91. Decode Ways  (0) 2022.12.08
[LeetCode] 83. Remove Duplicates from Sorted List  (0) 2022.10.27
[LeetCode] 70. Climbing Stairs  (0) 2022.08.19
[LeetCode] 69. Sqrt(x)  (0) 2022.08.19

댓글