Leetcode - Merge Sorted Array

Leetcode - Merge Sorted Array

์•Œ๊ณ ๋ฆฌ์ฆ˜ ๊ณต๋ถ€

Daily Leetcode

Hits

๋ฆฌํŠธ์ฝ”๋“œ๋ฅผ ํ’€์–ด๋ณด๋ ค ํ•œ๋‹ค. ๋ผ์ด๋ธŒ ์ฝ”ํ…Œ ๋Œ€๋น„์šฉ์œผ๋กœ ๋ง์ด๋‹ค. ์ผ๋‹จ ๋ชฉํ‘œ๋Š” 3๋‹ฌ ์•ˆ์— Top 150 ๋ฌธ์ œ๋ฅผ ํ‘ธ๋Š” ๊ฒƒ์ด๋‹ค. ๋ฌธ์ œ ํ’€์–ด๋ณด์ž.

๋ฌธ์ œ ๋งํฌ

โ›ณ๏ธ Naive Approach.

์‹œ๊ฐ„๋ณต์žก๋„์™€ ๊ณต๊ฐ„๋ณต์žก๋„๋ฅผ ๊ณ ๋ ค ์•ˆํ•˜๊ณ  ๊ฐ€์žฅ ๋‹จ์ˆœํ•œ ๋ฐฉ๋ฒ•์œผ๋กœ ๋จผ์ € ํ’€์–ด๋ณด์ž.

class Solution:
    def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
        """
        Do not return anything, modify nums1 in-place instead.
        """

        # Naive
        ptr = m

        for num in nums2:
            nums1[ptr] = num
            ptr += 1

        nums1.sort()

        # TC: O((m+n)log(m+n))
        # SC: O(1)

์ผ๋‹จ nums1 ๋ฐฐ์—ด์— nums2 ์›์†Œ๋“ค์„ ๋ชจ๋‘ ์˜ฎ๊ฒจ์ฃผ๊ณ  sort() ํ•จ์ˆ˜๋ฅผ ํ†ตํ•ด ์ •๋ ฌ์„ ์ง„ํ–‰ํ•˜๋Š” ๊ฒƒ์ด๋‹ค.

์ด๋ ‡๊ฒŒ ํ–ˆ์„ ๋•Œ Time Complexity : O((m+n)log(m+n)) ์ด๋ฉฐ Space Complexity ๋Š” O(1) ์ด๋‹ค.

์ด ์ฝ”๋“œ์˜ TC๋ฅผ ๋” ์ค„์ด๋Š” ๋ฐฉ๋ฒ•์ด ์žˆ์„๊นŒ?

โœ”๏ธŽ Best Approach

ํžŒํŠธ๋กœ ์ฃผ์–ด์ง„ ์ ๋“ค

  • ๋ฐ์ดํ„ฐ๋Š” ์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ์ด๋ฏธ ์ •๋ ฌ๋˜์–ด ์žˆ๋‹ค.
    • ์ถ”๊ฐ€์ ์ธ ์ •๋ ฌ์ด ํ•„์š” ์—†๋‹ค.
  • nums1์˜ ๊ฒฝ์šฐ ๋นˆ ๋ฐ์ดํ„ฐ๋“ค์€ 0์œผ๋กœ ๋‹ค ์ฑ„์›Œ์ ธ ์žˆ๋‹ค.

๊ทธ๋ ‡๋‹ค๋ฉด ๋‘ ๊ฐœ์˜ ํฌ์ธํ„ฐ๋ฅผ ์ด์šฉํ•ด์„œ nums[idx] = element ์—ฐ์‚ฐ ๋งŒ์„ ํ†ตํ•ด TC๋ฅผ ์ค„์ผ ์ˆ˜ ์žˆ์ง€ ์•Š์„๊นŒ?

class Solution:
    def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
        """
        Do not return anything, modify nums1 in-place instead.
        """

        # nums2 is empty
        if n == 0:
            return

        # Best Aprroach
        # use 2 pointer

        ptr1, ptr2 = m-1, n-1
        end = m+n-1

        while ptr2>=0:
            if ptr1>=0 and nums1[ptr1] > nums2[ptr2]:
                nums1[end] = nums1[ptr1]
                ptr1 -= 1
            else:
                nums1[end] = nums2[ptr2]
                ptr2 -= 1
            end -= 1

๋ณด๋‹ค์‹œํ”ผ ๋์—์„œ๋ถ€ํ„ฐ ํฐ ๊ฐ’์„ ๋„ฃ์–ด์ฃผ๊ณ  ์ž‡๋‹ค. ๋’ค์—์„œ๋ถ€ํ„ฐ ๋น„๊ตํ•˜๋ฉด์„œ ์ œ์ผ ํฐ ๊ฐ’์„ end ์ธ๋ฑ์Šค์— ๋„ฃ์–ด์ฃผ๊ณ  ์žˆ๋Š” ๊ฒƒ์ด๋‹ค. ์ด๋ ‡๊ฒŒ ๋˜๋ฉด ํฐ ๊ฐ’๋ถ€ํ„ฐ ๋’ค์—์„œ ์ •๋ ฌ์ด ๋˜๋ฉด์„œ ์ˆœํšŒ๋Š” ํ•œ๋ฒˆ๋งŒ ํ•˜๋ฉด ๋˜๋ฏ€๋กœ Time complexity : O(m+n) ์„ ๋งŒ์กฑํ•  ์ˆ˜ ์žˆ๋‹ค.

๊ฐ„๋‹จํ•œ ๋ฌธ์ œ์ด๋‚˜ ์ฐธ์‹ ํ•˜๋‹ค. ํ•ญ์ƒ ๊ณ ๋ฏผํ•˜์ž.