首页 > 其他 > 详细

Remove Duplicates from Sorted Array II

时间:2015-05-13 23:17:47      阅读:442      评论:0      收藏:0      [点我收藏+]
Follow up for "Remove Duplicates": What if duplicates are allowed at most twice?
For example,
Given sorted array nums = [1,1,1,2,2,3],

Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3. It doesn‘t matter what you leave beyond the new length.

方法与题目:Remove Duplicates from Sorted Array类似,同样是移除重复元素,但是允许元素最多重复两次,用一个变量记录重复次数,当不重复

时,变量清0,AC代码如下:

int removeDuplicates(int* nums, int numsSize) 
{
	//定义两个游标
	int i,j;
	//记数
	int index=0;
	if (numsSize==0)
	    return 0;
	i=0;
	for (j=1; j<numsSize; j++)
	{
		if (nums[i]==nums[j])
		{
			index++;
			if (index<2)
			{
				nums[++i]=nums[j];
			}
		}
		else
		{
			nums[++i]=nums[j];
			//计数清0
			index=0;
		}
	}
	return i+1;
}


Remove Duplicates from Sorted Array II

原文:http://blog.csdn.net/lsh_2013/article/details/45700773

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!