个人博客:https://luxialan.com

Remove Duplicates from Sorted Array II 分类: Leetcode(线性表) 2015-03-25 21:20 40人阅读 评论(0) 收藏

Remove Duplicates from Sorted Array II


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

版权声明:本文为博主原创文章,未经博主允许不得转载。

posted @ 2015-03-25 21:20  luxialan  阅读(116)  评论(0编辑  收藏  举报