- Remove Duplicates from Sorted Array II
https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/
删除元素,空间复杂度要求O(1)。
用了一个有限状态自动机的方法。状态机的状态为”当前元素重复的数目“,输入为”遍历到的元素相比新数组最后一个位置改变还是不改变“
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
length = len(nums)
i = 0
cnt = 1
j = 1
while j < length:
n = nums[j]
if cnt == 1:
if n == nums[i]:
i += 1
nums[i] = n
cnt += 1
else:
i += 1
nums[i] = n
cnt = 1
elif cnt == 2:
if n == nums[i]:
pass
else:
i += 1
nums[i] = n
cnt = 1
j += 1
return i+1
本文介绍了一种解决LeetCode上Remove Duplicates from Sorted Array II问题的方法,该方法使用有限状态自动机处理数组,确保每个元素最多出现两次,并保持O(1)的空间复杂度。

514

被折叠的 条评论
为什么被折叠?



