Problem solving/Algorithms

[LeetCode] Daily Challenge Merge Sorted Array (Python)

Young_A 2021. 1. 12. 14:49

๋ชฉ์ฐจ

    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() ํ•จ์ˆ˜๋ฅผ ํฌํ•จํ•˜๊ณ  ์žˆ๋‹ค.

    ๋ญ์ง€... ํ•ด๊ฒฐ์€ ํ–ˆ๋Š”๋ฐ ๊ต‰์žฅํžˆ ์ฐ์ฐํ•˜๋‹ค.