LeetCode 80. Remove Duplicates from Sorted Array II

来源:互联网 发布:2015年旅游业数据 编辑:程序博客网 时间:2024/05/18 01:35

1.题目描述

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.

2.解题思路

嗯,两个指针,扫一遍数组,O(n)
大概思路就是,前面的指针指向不出现不超过两次的,后面的指针指向出现超过两次的。

3.实现代码

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



0 0
原创粉丝点击