Remove Duplicates from Sorted Array II

来源:互联网 发布:java数据库代码生成器 编辑:程序博客网 时间:2024/06/10 16:37

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 1122 and 3. It doesn't matter what you leave beyond the new length.

解析:

从头到尾遍历,记录重复次数与排好序的位置

代码:

class Solution {public:    int removeDuplicates(vector<int>& nums) {        if (nums.empty())        return 0;        int curpos=1;        int times=1;        int cur=nums[0];        for (int i=1; i<nums.size(); i++)        {            if (nums[i]!=cur)            {                cur=nums[i];                nums[curpos++]=cur;                times=1;            }            else            {                if (times==1)                {                    times++;                    nums[curpos++]=cur;                }                else                {                    times++;                    continue;                }            }        }        return curpos;            }};



0 0
原创粉丝点击