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

leetcode_80题——Remove Duplicates from Sorted Array II(两个指针)

时间:2015-04-26 19:45:54      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:

Remove Duplicates from Sorted Array II

 Total Accepted: 38480 Total Submissions: 125235My Submissions

 

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

 

Hide Tags
 Array Two Pointers
Have you met this question in a real interview? 
Yes
 
No
 

Discuss

 

    这题与leetcode_26题——Remove Duplicates from Sorted Array (string)这道题差不多,设置两个指针i和j,j是从前往后遍历,若遇到与前面不同的则将j坐标的A[j]给前面A[i+1],然后将i+1,即前面的指针才往后移一位,这样依次往后,到最后的时候,i+1的值即为数组后来结果的大小,只是需要考虑可以容忍最多有两个相同的数字

#include<iostream>

using namespace std;

int removeDuplicates(int A[], int n) {
	if(n==0)
		return 0;
	if(n==1)
		return 1;
	if(n==2)
		return 2;

	int i=1;
	int j=2;

	while(j<n)
	{
		if(A[j]!=A[j-1])
		{
			if(j!=(i+1))
			{
				A[i+1]=A[j];
				i++;
				j++;
			}
			else
			{
				i++;
				j++;
			}
		}
		else
		{
			if(A[i]==A[i-1]&&A[i]==A[j])
				j++;
			else
			{
				if(j!=(i+1))
				{
					A[i+1]=A[j];
					i++;
					j++;
				}
				else
				{
					i++;
					j++;
				}
			}
		}
	}

	return i+1;
}
int main()
{
	int A[4]={1,2,2,2};
	cout<<removeDuplicates(A,4)<<endl;
	int n1=removeDuplicates(A,4);

	for(int i=0;i<n1;i++)
		cout<<A[i]<<endl;
}

  

 

leetcode_80题——Remove Duplicates from Sorted Array II(两个指针)

标签:

原文地址:http://www.cnblogs.com/yanliang12138/p/4458164.html

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