Remove Duplicates from Sorted Array II
ソート済み配列から重複要素を除去し、各要素を最大2回まで保持するTwo-Pointerアルゴリズムです。
from typing import List
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
"""
Remove duplicates from sorted array such that each unique element
appears at most twice. Modify nums in-place and return the new length.
Args:
nums (List[int]): Sorted integer array
Returns:
int: The length of modified array with each element appearing at most twice.
"""
n: int = len(nums)
if n <= 2:
return n
write: int = 2 # 最初の2要素は必ず残せる
for read in range(2, n):
if nums[read] != nums[write - 2]:
nums[write] = nums[read]
write += 1
return write
Current Step: 初期化
Read: - | Write: -
Action: 例を選択してください
配列を一回だけスキャンするため線形時間
追加の配列を使わずポインタ変数のみ
if nums[read] != nums[write - 2]:
なぜ write-2 を見るのか?
write-2は結果領域の「2つ前の要素」を指す
nums[write-2]と同じなら3個目の重複