leetcode之Remove Duplicates from Sorted Array II

来源:互联网 发布:淘宝直通车开了就亏 编辑:程序博客网 时间:2024/06/08 09:06

题目:

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) {        int start = 0;        int end = 1;        int size = nums.size();        if(size <= 2)            return size;        int cnt = 1;        while(end < size)        {            if(nums[start] == nums[end])            {                if(cnt < 2)                {                    nums[++start] = nums[end++];                }                else                {                    end++;                }                cnt++;            }            else            {                nums[++start] = nums[end++];                cnt = 1;            }        }        return start + 1;    }};

0 0
原创粉丝点击