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

Remove Duplicates from Sorted Array II

时间:2015-05-13 23:18:20      阅读:331      评论:0      收藏:0      [点我收藏+]

标签:c语言   leetcode   

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

标签:c语言   leetcode   

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

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