Solution 1
本题可以认为是Remove Duplicates from Sorted Array的变体,主要的区别就是同类元素可以出现不超过两次。本题的框架下,相同元素必然连续分布,因此只需要判断当前元素是否和已归置部分的倒数第二个元素相同进行取舍。具体实现中,一些判定部分要因此进行调整。
- 时间复杂度: O ( N ) O(N) O(N),其中 N N N为序列长度,线性遍历
- 空间复杂度: O ( 1 ) O(1) O(1),仅维护常数个状态量
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int length = nums.size();
if (length <= 2) {
// 前两个无论怎么样都满足要求
return length;
}
int posA = 2, posB = 2;
// 一个是下面的判定条件从0会出问题。而从2开始则因为问题本身的性质而变得无所谓
while (posB < length) {
if (nums[posA - 2] != nums[posB]) {
// 至多出现两次,必然连续出现
nums[posA] = nums[posB];
posA++;
}
posB++;
}
return posA;
}
};
Solution 2
Solution 1的Python实现
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
length = len(nums)
if length <= 2: return length
posA, posB = 2, 2
while posB < length:
if nums[posA - 2] != nums[posB]:
nums[posA] = nums[posB]
posA += 1
posB += 1
return posA