Remove Duplicates from Sorted Array II -- leetcode

来源:互联网 发布:爱淘客网站源码 编辑:程序博客网 时间:2024/06/05 08:35

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) return 0;        int count = 1;        int idx = 0;        for (int i=1; i<n; i++) {            if (A[idx] == A[i]) {                ++count;                if (count <= 2)                    A[++idx] = A[i];            }            else {                A[++idx] = A[i];                count = 1;            }        }                return idx+1;    }};


0 0
原创粉丝点击