Remove Duplicates from Sorted Array II

来源:互联网 发布:sql plus是什么 编辑:程序博客网 时间:2024/05/16 01:50

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].


public class Solution {
    public int removeDuplicates(int[] A) {
       if(A.length<=2){
         return A.length;  
       }else{
           int count =1;           
           int num=1;
           int val=A[0];
           for(int i=1;i<A.length;i++){
               if(A[i]==val){
                   if(count<2){
                   count++;
                       A[num++]=val;    
                   }
               }else{
                   val=A[i];
                   A[num++]=val;
                   count=1;   
               }             
           }
           return num;
       }
   }
}

0 0