您的位置:首页 > 其它

Remove Duplicates from Sorted Array II -- leetcode

2015-04-14 16:41 381 查看
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;
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: