반응형
Notice
Recent Posts
Recent Comments
- Today
- Total
작심삼일
[LeetCode] 88 | Merge Sorted Array | Python 본문
728x90
반응형
문제 링크: https://leetcode.com/problems/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 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.length == m + n
- nums2.length == n
- 0 <= m, n <= 200
- 1 <= m + n <= 200
- $-10^9$ <= nums1[i], nums2[j] <= $10^9$
내 풀이
nums1 array 뒤쪽이 0으로 채워져있다는 점을 기억하자.
앞에서부터 작은 숫자를 채우는 대신, 뒤에서부터 큰 숫자를 채운다고 생각한다.
코드
class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
k = len(nums1)
while m > 0 and n > 0:
if nums1[m-1] > nums2[n-1]:
nums1[k-1] = nums1[m-1]
m -= 1
else:
nums1[k-1] = nums2[n-1]
n -= 1
k -= 1
while n > 0:
nums1[k-1] = nums2[n-1]
k -= 1
n -= 1
728x90
반응형
'스터디 > 코테' 카테고리의 다른 글
[LeetCode] 167 | Two Sum II | Input Array Is Sorted | Python (0) | 2022.06.09 |
---|---|
[LeetCode] 1332 | Remove Palindromic Subsequences | Python (0) | 2022.06.08 |
[LeetCode] 867 | Transpose Matrix | Python (0) | 2022.06.02 |
[LeetCode] 29 | Divide Two Integers | Python (0) | 2022.05.30 |
[LeetCode] 191 | Number of 1 Bits | Python (0) | 2022.05.26 |
Comments