首页 > 代码库 > leetcode 题解:Remove Duplicates from Sorted Array II(已排序数组去三次及以上重复元素)

leetcode 题解: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].

说明:

     1)设个标志可实现

实现:

 1 class Solution { 2 public: 3     int removeDuplicates(int A[], int n) { 4         if(0==n)  return 0; 5         int B[n],k=0,flag=1; 6         for(int i=0;i<n;i++)  7             B[i]=0; 8         B[0]=A[0]; 9         for(int i=1;i<n;i++)10         {11             if(B[k]==A[i])12                flag++;13             else14                flag=1;15             if(flag<3)16               B[++k]=A[i];17         }18         for(int i=0;i<=k;i++)19             A[i]=B[i];20         return k+1;21     }22 };