[Leetcode] 80. Remove Duplicates from Sorted Array II
[Leetcode] 80. Remove Duplicates from Sorted Array II

[Leetcode] 80. Remove Duplicates from Sorted Array II

์–ธ์–ด
Python
C
๋‚œ์ด๋„
๋‹ค์‹œ ํ’€์–ด๋ณด๊ธฐ
๋‹ค์‹œ ํ’€์–ด๋ณด๊ธฐ
์•Œ๊ณ ๋ฆฌ์ฆ˜ ์œ ํ˜•
์ž‘์„ฑ์ž
๋ฐ•์šฉ์„ฑ๋ฐ•์šฉ์„ฑ
์ƒ์„ฑ ์ผ์‹œ
2024๋…„ 09์›” 11์ผ
floatFirstTOC: right

๐Ÿ–ฅ๏ธย ์‹œ์ž‘ํ•˜๋ฉฐ

๋ณด์ž๋งˆ์ž ํˆฌํฌ์ธํ„ฐ๊ฐ€ ์ƒ๊ฐ๋‚˜๋Š” ๋ฌธ์ œ๋‹ค. slow ์™€ fast ๋ฅผ ์ง€์ •ํ•œ ํ›„ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ๋‹ค.
ย 

โš™๏ธย Python

from typing import List class Solution: def removeDuplicates(self, nums: List[int]) -> int: if len(nums) <= 2: return len(nums) # ๊ธธ์ด๊ฐ€ 2 ์ดํ•˜์ผ ๊ฒฝ์šฐ ์ด๋ฏธ ์กฐ๊ฑด์„ ๋งŒ์กฑ # Two pointer approach slow = 2 # ์ฒ˜์Œ ๋‘ ๊ฐœ๋Š” ๊ทธ๋Œ€๋กœ ๋‘๋ฏ€๋กœ slow๋Š” 2๋ถ€ํ„ฐ ์‹œ์ž‘ for fast in range(2, len(nums)): # fast ํฌ์ธํ„ฐ๊ฐ€ ๊ฐ€๋ฆฌํ‚ค๋Š” ๊ฐ’์ด slow ํฌ์ธํ„ฐ ๋ฐ”๋กœ ์•ž ๋‘ ๊ฐœ์˜ ๊ฐ’๊ณผ ๋‹ค๋ฅผ ๋•Œ if nums[fast] != nums[slow - 2]: nums[slow] = nums[fast] # ๊ฐ’์„ ์˜ฎ๊น€ slow += 1 # ์ค‘๋ณต์„ ํ—ˆ์šฉํ•œ ์œ„์น˜๋ฅผ ์ฆ๊ฐ€ return slow # slow ํฌ์ธํ„ฐ๊ฐ€ ์ค‘๋ณต์„ ์ œ๊ฑฐํ•œ ๋ฐฐ์—ด์˜ ๊ธธ์ด๋ฅผ ๋ฐ˜ํ™˜ # ์˜ˆ์ œ ํ…Œ์ŠคํŠธ sol = Solution() print(sol.removeDuplicates([0, 0, 1, 1, 1, 1, 2, 3, 3]))
ย 
ํˆฌํฌ์ธํ„ฐ๋ฅผ ํ™œ์šฉํ•˜์ง€ ์•Š๊ณ  ๋‹ค๋ฅธ ๋ฐฉ๋ฒ•์œผ๋กœ ํ•ด๊ฒฐ๋„ ๊ฐ€๋Šฅํ•˜๋‹ค.
class Solution: def removeDuplicates(self, nums: List[int]) -> int: if not nums: return 0 idx = 1 count = 1 for i in range(1, len(nums)): if nums[i] == nums[i - 1]: count += 1 else: count = 1 if count <= 2: nums[idx] = nums[i] idx += 1 return idx

๐Ÿ“Œย ์†Œ๊ฐ

๋Œ“๊ธ€

guest