leecode 解题总结:80. Remove Duplicates from Sorted Array II

本文介绍了一个C++实现的算法,该算法用于从已排序数组中去除多余的重复元素,最多保留两个重复项。通过使用计数器跟踪每个元素的出现次数,并标记超出限制的元素进行移除,最终返回处理后的数组长度。
#include <iostream>
#include <stdio.h>
#include <vector>
using namespace std;
/*
问题:
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 1, 1, 2, 2 and 3. It doesn't matter what you leave beyond the new length.

分析:这次是如果有重复的元素,至少保留两个重复的元素。
可以遍历到每个元素的时候,设定一个计数器,当计数器为3的时候,就记录此时位置为待删除位置。
一遍扫描后,得到所有删除的位置,在从后向前遍历,删除待删除位置的上元素

输入:
6(数组元素个数)
1 1 1 2 2 3
输出:
5
*/

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        if(nums.empty())
		{
			return 0;
		}
		int size = nums.size();
		vector<int> deleteFlags(size , 0);//0表示不删除
		int count = 1;
		int value = nums.at(0);
		for(int i = 1 ; i < size ; i++)
		{
			//找到重复的元素,累加计数器
			if(nums.at(i) == value)
			{
				count++;
				//找到待删除位置
				if(count > 2)
				{
					deleteFlags.at(i) = 1;
				}
			}
			//非重复元素,重新设定计数器和元素
			else
			{
				value = nums.at(i);
				count = 1;
			}
		}
		//从后向前删除指定位置上的元素
		for(int i = size - 1 ; i >= 0 ; i--)
		{
			if(1 == deleteFlags.at(i))
			{
				nums.erase(nums.begin() + i , nums.begin() + i + 1);
			}
		}
		if(nums.empty())
		{
			return 0;
		}
		int result = nums.size();
		return result;
    }
};

void print(vector<int>& result)
{
	if(result.empty())
	{
		cout << "no result" << endl;
		return;
	}
	int size = result.size();
	for(int i = 0 ; i < size ; i++)
	{
		cout << result.at(i) << " " ;
	}
	cout << endl;
}

void process()
{
	 vector<int> nums;
	 int value;
	 int num;
	 Solution solution;
	 vector<int> result;
	 while(cin >> num )
	 {
		 nums.clear();
		 for(int i = 0 ; i < num ; i++)
		 {
			 cin >> value;
			 nums.push_back(value);
		 }
		 int result = solution.removeDuplicates(nums);
		 cout << result << endl;
		 //print(nums);
	 }
}

int main(int argc , char* argv[])
{
	process();
	getchar();
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值