[leetcode] 80. Remove Duplicates from Sorted Array II 解题报告

来源:互联网 发布:阿里云华南地区是哪里 编辑:程序博客网 时间:2024/05/16 06:02

题目链接:https://leetcode.com/problems/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.


思路:因为有些元素需要删除掉,可以将后面的元素往前移动,并且需要一个索引来标记当前可以赋值的位置.每遇到一个新元素就开始计数,如果其个数小于3的地方就赋值并且移动索引位置,否则就不管.

代码如下:

class Solution {public:    int removeDuplicates(vector<int>& nums) {        if(nums.size() ==0) return 0;        int ans = 1, old = nums[0], cnt = 1, i= 0;        while(++i < nums.size())        {            if(nums[i] != old) nums[ans++]=nums[i], cnt=1, old=nums[i];            else if(++cnt < 3) nums[ans++]=nums[i];        }        return ans;    }};


0 0
原创粉丝点击