[leetcode-80]Remove Duplicates from Sorted Array II(C)

来源:互联网 发布:淘宝店铺口令怎么生成 编辑:程序博客网 时间:2024/05/17 21:45

问题描述:
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.

分析:这里需要加一个计数的变量。

代码如下:8ms

int removeDuplicates(int* nums, int numsSize) {    int res = 0;    int count = 1;        for(int i = 0;i<numsSize;i++){        while(i>0 && i<numsSize && nums[i] == nums[i-1] && ++count>2) i++;        if(i==numsSize)            break;        if(nums[i]!=nums[i-1])            count = 1;        nums[res++] = nums[i];        }    return res;}
0 0