Remove Duplicates from Sorted Array II

来源:互联网 发布:阿迪达斯淘宝精仿店 编辑:程序博客网 时间:2024/06/06 02:16

Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?

For example,
Given sorted array A = [1,1,1,2,2,3],

Your function should return length = 5, and A is now [1,1,2,2,3].


这题也可以用双指针的思想,前面一个指针来进行筛选,后面的指针输出。

class Solution {public:    int removeDuplicates(int A[], int n) {        if(n<2) return n;                int flag = 0;        int first = 0;        int second = 1;        while(second<n)        {            if(A[second]==A[second-1])            {                if(flag == 1)                {                    second++;                    continue;                }                else                {                    flag = 1;                    A[++first] = A[second++];                }            }            else            {                flag = 0;                A[++first] = A[second++];            }        }                return first+1;    }};


0 0
原创粉丝点击