[leetcode] Remove Duplicates from Sorted Array II

来源:互联网 发布:linux 报文发送工具 编辑:程序博客网 时间:2024/09/21 06:35

From : 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.

Hide Tags
 Array Two Pointers


Solution : 

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


0 0
原创粉丝点击