Leetcode - Remove Duplicates from Sorted Array II

Leetcode - Remove Duplicates from Sorted Array II

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

Daily Leetcode

Hits

๋ฌธ์ œ ๋งํฌ

๐Ÿƒโ€โ™‚๏ธโ€โžก๏ธ Naive Solution

๋ฌธ์ œ์˜ ์กฐ๊ฑด ์ค‘ ํ•˜๋‚˜๊ฐ€ ์ถ”๊ฐ€์ ์ธ Space๋ฅผ ์“ฐ์ง€ ๋ง๊ณ  ์ง„ํ–‰ํ•˜๋ผ๊ณ  ๋‚˜์™€์žˆ์ง€๋งŒ ์ถ”๊ฐ€์ ์ธ ๊ณต๊ฐ„์„ ์“ฐ๋Š” Naive ํ•œ ๋ฐฉ์‹์˜ ์†”๋ฃจ์…˜์€ ์•„๋ž˜์™€ ๊ฐ™๋‹ค

class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        # Naive Solution
        num_cnt = dict()
        wIdx = 0

        for i in range(len(nums)):
            cnt = num_cnt.get(nums[i], 0)
            if cnt < 2:
                nums[wIdx] = nums[i]
                num_cnt[nums[i]] = cnt+1
                wIdx += 1
        
        return wIdx
  • Time Complexity : O(n)
  • Space Complexity : O(n)

๋ณด์‹œ๋‹ค์‹œํ”ผ num_cnt ๋”•์…”๋„ˆ๋ฆฌ๋ฅผ ์ด์šฉํ•˜์—ฌ ์ง€๊ธˆ๊นŒ์ง€ ์›์†Œ๊ฐ€ ๋ช‡ ๋ฒˆ ๋‚˜์™”๋Š”์ง€๋ฅผ ์ €์žฅํ•˜๊ณ  2๋ฒˆ ๋ฏธ๋งŒ์œผ๋กœ ๋‚˜์™”๋‹ค๋ฉด ๊ทธ ์ž๋ฆฌ์— ์›์†Œ๋ฅผ ๋„ฃ์–ด์ฃผ๋Š” ๋ฐฉ์‹์œผ๋กœ ์ง„ํ–‰ํ•œ๋‹ค. ์ถ”ํ›„ ๋‚˜์˜ฌ ์†”๋ฃจ์…˜๋ณด๋‹ค ์ด ๋ฐฉ๋ฒ•์ด ์‹ค์ œ Runtime ์†๋„๊ฐ€ ๋น ๋ฅด๊ฒŒ ๋‚˜์˜ค๊ธฐ๋Š” ํ•œ๋‹ค.

๐ŸŽธ Reduce Space Complexity

์ด์ œ ๋ฉด์ ‘๊ด€์ด Space Complexity๋ฅผ O(1)๋กœ ์ฒ˜๋ฆฌํ•ด๋‹ฌ๋ผ๊ณ  ๋ถ€ํƒํ–ˆ์„ ๋•Œ, ์–ด๋–ป๊ฒŒ ํ•˜๋ฉด ๋ ๊นŒ?

ํ•ต์‹ฌ์€ 2๋ฒˆ ๋ฐ˜๋ณต๋๋‚˜๋ฅผ ์ธ๋ฑ์Šค๋ฅผ ์ฒดํฌํ•˜๋Š” ๊ฒƒ์ด๋‹ค. ํ˜„ ์‹œ์  wIdx-2 ์ธ๋ฑ์Šค์˜ ์›์†Œ๊ฐ€ ์ง€๊ธˆ๊ณผ ๊ฐ™๋‹ค๋ฉด ๊ทธ๊ฑด 2๋ฒˆ ๋ฐ˜๋ณต๋๋‹ค๋Š” ๋œป์ด๋‹ค.

class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        wIdx = 2

        for i in range(2, len(nums)):
            if nums[wIdx-2] != nums[i]:
                nums[wIdx] = nums[i]
                wIdx += 1
        return wIdx

์ฝ”๋“œ๋ฅผ ๋ณด๊ฒŒ๋œ๋‹ค๋ฉด wIdx๋ฅผ 2๋ถ€ํ„ฐ ์‹œ์ž‘ํ•˜๋ฉด์„œ ํ•ด๋‹น ์—˜๋ ˆ๋จผํŠธ๊ฐ€ 2๋ฒˆ ๋ฐ˜๋ณต๋๋Š”์ง€๋ฅผ ์ฒดํฌํ•œ๋‹ค. ์ด ๋ฐฉ๋ฒ•์œผ๋กœ ์ง„ํ–‰ํ•  ์‹œ ์ถ”๊ฐ€์ ์ธ ๊ณต๊ฐ„์—†์ด O(1) ๋งŒ์— ๋ฌธ์ œ๋ฅผ ํ’€ ์ˆ˜ ์žˆ๋‹ค.