首页 > 代码库 > Remove Duplicates from Sorted Array II <leetcode>

Remove Duplicates from Sorted Array II <leetcode>

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 class Solution { 2 public: 3     int removeDuplicates(int A[], int n) { 4         if(0==n)  return 0; 5         else if(1==n)  return 1; 6         else if(2==n)  return 2; 7         8         int count=1; 9         int pre=A[0];10         for(int i=1;i<n;i++)11         {12             if(A[i]==pre)13             {14                 count++;15                 if(count>2)16                 {17                     for(int j=i;j<n-1;j++)18                     {19                         A[j]=A[j+1];20                     }21                     A[n-1]=pre;22                     i--;23                     n--;24                 }25             }26             else if(A[i]!=pre)27             {28                 count=1;29                 pre=A[i];30             }31         }32         return n;33     }34 };

 

Remove Duplicates from Sorted Array II <leetcode>