码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode_26_Remove Duplicates from Sorted Array

时间:2015-02-12 18:30:37      阅读:113      评论:0      收藏:0      [点我收藏+]

标签:leetcode   c++   array   

欢迎大家阅读参考,如有错误或疑问请留言纠正,谢谢技术分享


Remove Duplicates from Sorted 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].


//vs2012测试代码
#include<iostream>

using namespace std;

#define n 5

int main()
{
	int A[n];
	for(int i=0; i<n; i++)
		cin>>A[i];

	//要考虑空数组的情况
	if(n==0)
		return 0;

	int start=0;
	for(int i=0; i<n-1; i++)
	{
		if( A[i]!=A[i+1])
		{
			A[start] = A[i];
			start++;
		}
	}
	A[start] = A[n-1];
	start++;

	//for(int j=start; j<n; j++)
	//	A[j]=0;

	cout<<start<<endl;
	for(int j=0; j<start; j++)
		cout<<A[j];

	return start;
}

//方法一:自测accepted
class Solution {
public:
    int removeDuplicates(int A[], int n) {
	//要考虑空数组的情况
	if(n==0)
		return 0;

	int start=0;
	for(int i=0; i<n-1; i++)
	{
		if( A[i]!=A[i+1])
		{
			A[start] = A[i];
			start++;
		}
	}
	A[start] = A[n-1];
	start++;

	//for(int j=start; j<n; j++)
	//	A[j]=0;

	cout<<start<<endl;
	for(int j=0; j<start; j++)
		cout<<A[j];

	return start;
    }
};

//方法二:参考其他
class Solution {
public:
	int removeDuplicates(int A[], int n) {
		// Start typing your C/C++ solution below
		// DO NOT write int main() function
		if(0 == n) return 0;
		int len = 1;
		for (int i = 1; i < n; ++i)
		{
			if(A[i] != A[len-1])
				A[len++] = A[i];
		}
		return len;
	}
};

leetcode_26_Remove Duplicates from Sorted Array

标签:leetcode   c++   array   

原文地址:http://blog.csdn.net/keyyuanxin/article/details/43764421

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!