Leetcode - Remove Duplicates from Sorted Array II
์๊ณ ๋ฆฌ์ฆ ๊ณต๋ถ
Daily Leetcode
๐โโ๏ธโโก๏ธ 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) ๋ง์ ๋ฌธ์ ๋ฅผ ํ ์ ์๋ค.