๋ชฉ์ฐจ
LeetCode - Daily Challenge - Merge Sorted Array
Problem Description
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
The number of elements initialized in nums1 and nums2 are m and n respectively.
You may assume that nums1 has enough space (size that is equal to m + n) to hold additional elements from nums2.
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]
Example 2:
- Input: nums1 = [1], m = 1, nums2 = [], n = 0
- Output: [1]
Constraints:
- 0 <= n, m <= 200
- 1 <= n + m <= 200
- nums1.length == m + n
- nums2.length == n
- -109 <= nums1[i], nums2[i] <= 109
My Solution (Python)
class Solution(object):
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: None Do not return anything, modify nums1 in-place instead.
"""
if n == 0:
return nums1
for i in range(m, n + m):
nums1[i] = nums2[i-m]
nums1.sort()
return nums1
1. nums2 ๊ฐ ๋น์ด์์ผ๋ฉด nums1 ๋ฐํ
2. nums1 ๋ท ์ชฝ์ 0๋ก ์ฑ์์ ธ ์๋ ๋ถ๋ถ์ nums2์ ์์๋ก ์ฑ์ฐ๊ธฐ
3. nums1๋ฅผ ์ ๋ ฌํจ
4. nums1 ๋ฐํ
์ฒ์์ ์ด ๋ฐฉ๋ฒ์ผ๋ก ์ ๊ทผํ๋๋ฐ, vscode์์๋ ์ ๋๊ณ leetcode์์๋ ์ ์๋์๋ค.
์ค๊ฐ ๊ณผ์ ์ ๋ชจ๋ ์ ์ฅํ์๋๋ฐ ์ค์๋ก ๋ ๋ ธ๋ค.
ํน์๋ ํด์ ๋ค์ ์๋ํด๋ณด์๋๋ ์ ๋๋ค.
์ค๊ฐ์ ์์์ฑ๊ฒ len(), range() ๊ทธ๋ฆฌ๊ณ sorted() ํจ์๊ฐ ์ ์ฉ๋์ง ์์๋ค๋ ๊ฒ.
๋ด๊ฐ ์ค์๋ก ์์ฑํ๋ค๊ธฐ์๋ vscode์์๋ ๊ฒฐ๊ณผ๊ฐ ์ ๋์ค๋๋ฐ leetcode์์ runํ๋ฉด ๊ฒฐ๊ณผ๊ฐ ๋ค๋ฅด๊ฒ ๋์จ๋ค๊ณ ? ๋ง์ด ์๋๋ค๊ณ ์๊ฐํ๋ค.
๊ทธ๋ฐ๋ฐ ๋ง์ง๋ง์ Accepted Submission์ range() ํจ์๋ฅผ ํฌํจํ๊ณ ์๋ค.
๋ญ์ง... ํด๊ฒฐ์ ํ๋๋ฐ ๊ต์ฅํ ์ฐ์ฐํ๋ค.

'Problem solving > Algorithms' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
| [LeetCode]Daily Challenge: Boats to Save People (Python) (0) | 2021.01.13 |
|---|---|
| [LeetCode] Daily Challenge: Add Two Numbers (Python) (0) | 2021.01.13 |
| [LeetCode] 1684. Count the Number of Consistent Strings (Python) (0) | 2021.01.10 |
| [LeetCode] 1678. Goal Parser Interpretation (Python) (0) | 2021.01.10 |
| [LeetCode] 1603. Design Parking System (Python) (0) | 2021.01.10 |