https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/
移除重複的,最多留兩個,回傳長度
Example 1:
Input: nums = [1,1,1,2,2,3]
Output: 5, nums = [1,1,2,2,3,_]
Explanation: Your function should return k = 5, with the first five elements of nums being 1, 1, 2, 2 and 3 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).
Example 2:
Input: nums = [0,0,1,1,1,1,2,3,3]
Output: 7, nums = [0,0,1,1,2,3,3,_,_]
Explanation: Your function should return k = 7, with the first seven elements of nums being 0, 0, 1, 1, 2, 3 and 3 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).
May 4, 2024
初始化兩個指針,指向0
第一個先不動,第二個持續走到相同數字的最後一個(下一個與當前不同),中間計算相同數字出現幾次
把第二個指針與第一個指針的值交換(第一次換沒意義,但之後就有了),交換次數取覺得出現次數,最多2次
每次交換後,左指針往右走
最後回傳左指針
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
l, r = 0, 0
while r < len(nums):
count = 1
while r + 1 < len(nums) and nums[r] == nums[r + 1]:
r += 1
count += 1
for _ in range(min(2, count)):
nums[l] = nums[r]
l += 1
r += 1
return l