Remove_Duplicates_from_sorted_array_2

1.问题描述

LeetCode:
Follow up for ”Remove Duplicates”: What if duplicates are allowed at most twice? For example, Given sorted array A = [1,1,1,2,2,3], Your function should return length = 5, and A is now [1,1,2,2,3]

2.问题分析

在已排序的数组中,移除出现次数大于二的数字(最多保留两个)。
使用快慢索引:

0、如果数组长度不大于2,直接返回数组长度;
1、索引i负责从第3个元素往后依次遍历整个数组;
2、索引index从第3个元素往后,负责记录去重之后数组长度(永远指向去重后数组最后一个元素后一个位置)3、不断比较索引i和索引(index-2)位置的数是否相等:
	不相等则将索引i指向的数复制到索引index指向的位置,然后将index加一。
4、最后返回index。

3.代码

#include <iostream>
using namespace std;
class Solution
{
public:
	int removeDuplicates(int A[], int n)
	{
		if(n <= 2) return n;

		int index = 2;
		for(int i = 2; i < n; i++)
		{
			if(A[i] != A[index-2])
				A[index++] = A[i];
		}
		return index;
	}
};

//测试
int main(int argc, char* argv[])
{
	Solution A;
	int b[7] = {1,2,2,2,3,3,3};
	int length = A.removeDuplicates(b,7);
	cout << length << endl;
	system("pause");
	return 0;

}

4.总结

本题的关键在于加一个变量记录一下元素出现的次数。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值