leetcode 80:Remove Duplicates from Sorted Array II

本文介绍了一种针对已排序数组中元素允许最多重复两次的去重算法,提供了两种解决方案,一种通过移动数据实现,另一种更为高效,仅通过记录元素出现次数并在必要时更新数组内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?

For example,
Given sorted array nums = [1,1,1,2,2,3],

Your function should return length = 5, with the first five elements of nums being 1122 and 3. It doesn't matter what you leave beyond the new length.

思路:

因为已经排好序了,我们只需看每个元素相同的个数,超过2个我们就删除多余的,然后将后面的元素往前移动,移动操作直接借用STL的move来完成。

但是从后面开始检测,更节省时间。

实现如下:

class Solution {
public:
	int removeDuplicates(vector<int>& nums) {
		int size = nums.size();
		if (size < 3) return size;
		int count = 1,flag=0;
		vector<int>::iterator last = nums.end();
		for (vector<int>::iterator i = nums.begin() + 1; i < last; ++i)
		{
			while (i != last && *i == *(i - 1))
			{
				++count;
				++i;
				flag = 1;
			}
			if (count >= 3)
			{
				last -= count - 2;
				move(i, nums.end(), i - count + 2);
				i -= (count - 2);
				count = 1;
			}
			else count = 1;
			if (flag == 1)
			{
				flag = 0;
				--i;
			}
		}
		return (last - nums.begin());
	}
};

下面提供更快、更简洁的方法,不需要移动数据。

记录元素个数,当第i个元素与前两个不相同时,就将该元素存到相应位置。

时间复杂度:O(n)

class Solution {
public:
	int removeDuplicates(vector<int>& nums) {
		int size = nums.size();
		if (size < 3) return size;
		int rear = 1;
		for (int i = 2; i < size; ++i)
			if (!(nums[i] == nums[rear] && nums[i] == nums[rear - 1])) nums[++rear] = nums[i];
		return rear + 1;
	}
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值