Vulkan

Remove duplicates from array

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

#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;
		while(pn < n)
		{
			if (a[p] == a[pn])
			{
				pn++;
			}
			else
			{
				p++;
				a[p] = a[pn];
				pn++;
			}
		}
		return p+1;
	}

//	int removeSTL(int a[], int n)
//	{
//		return distance(a, unique(a, a + n));
//	}
};

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

	Solution s;
	cout<<s.removeDuplicates(a,12)<<endl;
//	cout<<s.removeSTL(a,12)<<endl;

	return 0;
}

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

导航