Vulkan

Remove duplicates from array II

//Given a sorted array, remove the duplicates in place such that each element appear only
//	once and return the new length.
//	Do not allocate extra space for another array, you must do this in place with constant memory.
//	For example, Given input array A = [1,1,2],
//	Your function should return length = 2, and A is now [1,2].


//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]

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

class Solution 
{
public:
	int removeDuplicates(int a[], int n) 
	{
		if (n < 2)
		{
			return n;
		}

		int p = 0;
		int pn = 1;
		int flag = 0;

		while(pn < n)
		{
			if (a[p] == a[pn])
			{
				if(flag <1)
				{
					p++;
					a[p] = a[pn];
					pn++;
					flag++;
				}
				else
				{
					pn++;
					flag ++;
				}
			}
			else
			{
				p++;
				a[p] = a[pn];
				pn++;
				flag = 0;
			}
		}
		return p+1;
	}
};

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];
				index++;
			}
		}
		return index++;
	}
};


int main()
{
	int a[12] = {1,1,2,2,2,4,4,7,7,7,8,9};

	Solution s;
	int t = s.removeDuplicates(a,12);
	cout<<t<<endl;
	for (int i = 0; i<t; i++)
	{
		cout<<a[i]<<endl;
	}
	return 0;
}

posted on 2014-06-04 10:43  Vulkan  阅读(90)  评论(0编辑  收藏  举报

导航