您的位置:首页 > 其它

LeetCode 80

2016-05-20 12:48 357 查看
Remove Duplicates from Sorted Array II

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.

/*************************************************************************
> File Name: LeetCode080.c
> Author: Juntaran
> Mail: JuntaranMail@gmail.com
> Created Time: Tue 17 May 2016 20:54:02 PM CST
************************************************************************/

/*************************************************************************

Remove Duplicates from Sorted Array II

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.

************************************************************************/

#include <stdio.h>

int removeDuplicates(int* nums, int numsSize)
{
if(numsSize < 2)
{
return numsSize;
}

int count = 1;
int j = 1;
int i;

for( i=1; i<numsSize; i++ )
{
if( nums[i] == nums[i-1] )
{
count ++;
if( count < 3 )
{
nums[j++] = nums[i];
}
else
{
printf("***\n");
}
printf("i=%d j=%d nums[i]=%d nums[j]=%d\n", i,j,nums[i],nums[j]);
printfNums(nums,numsSize);
}
else
{
nums[j++] = nums[i];
count = 1;
printf("i=%d j=%d nums[i]=%d nums[j]=%d\n", i,j,nums[i],nums[j]);
printfNums(nums,numsSize);
}
}
return j;

}

void printfNums( int* nums, int numsSize )
{
int i;
for( i=0; i<numsSize; i++ )
{
printf("%d ", nums[i]);
}
printf("\n");
}

int main()
{
int nums[] = { 1, 2, 3, 3, 3, 5, 5, 5 };
int numsSize = 8;

int ret = removeDuplicates( nums, numsSize );
printf("%d\n", ret);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: