/**
 *	Follow up for "Remove Duplicates":
 *	What if duplicates are allowed at most twice?
 *
 *	For example,
 *	Given sorted array nums = [1,1,1,2,2,3],
 *
 *	Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3.
 *	It doesn't matter what you leave beyond the new length.
 *	
 *	Author: matao
 *
 */

public class RemoveDuplicatesFromSortedArrayII {
	public static int removeDuplicates(int[] nums) {
        if(nums == null || nums.length == 0) {
        	return 0;
        }

        int cur = 0;
        int i ,j;
        for(i = 0; i < nums.length;){
            int now = nums[i];
            for( j = i; j < nums.length; j++){
                if(nums[j] != now)
                    break;
                if(j-i < 2)
                    nums[cur++] = now; 
            }
            i = j;
        }
        return cur;
    }

    public static void main(String[] args) {
    	int[] nums1 = {1, 1, 2};
    	System.out.println(removeDuplicates(nums1));

    	int[] nums2 = {1};
    	System.out.println(removeDuplicates(nums2));

    	int[] nums3 = {1, 1, 2, 2};
    	System.out.println(removeDuplicates(nums3));

    	int[] nums4 = {1, 1, 2, 2, 2, 3};
    	System.out.println(removeDuplicates(nums4));

    	int[] nums5 = {-14,-14,-13,-13,-13,-13,-13,-13,-13,-12,-12,-12,-12,-11,-10,-9,-9,-9,-8,-7,-5,-5,-5,-5,-4,-3,-3,-2,-2,-2,-2,-1,-1,-1,-1,-1,0,1,1,1,1,2,2,2,3,3,3,4,4,4,4,5,5,5,6,6,6,6,7,8,8,8,9,9,9,10,10,10,11,11,11,12,12,12,13,14,14,14,14,15,16,16,16,18,18,18,19,19,19,19,20,20,20,21,21,21,21,21,21,22,22,22,22,22,23,23,24,25,25};
    	System.out.println(removeDuplicates(nums5));
    }
}
@@ -531,60 +531,44 @@
    i
-nt cur = 0;%0A        int i ,j;%0A        for(i = 0; i %3C
+f(nums.length %3C 2) %7B%0A        %09return
  num
@@ -576,23 +576,28 @@
 .length;
-)%7B
 %0A    
+    %7D%0A%0A
         
@@ -604,27 +604,49 @@
 int 
-now = nums%5Bi%5D;%0A    
+i = 0;%0A        boolean isRepeat = false;%0A
     
@@ -656,15 +656,19 @@
  for
-(
+ (int
  j = 
-i
+1
 ; j 
@@ -686,16 +686,17 @@
 th; j++)
+ 
 %7B%0A      
@@ -697,24 +697,17 @@
         
-        
+%09
 if(nums%5B
@@ -717,85 +717,157 @@
 != n
-ow)%0A                    break;%0A                if(j-i %3C 2)%0A          
+ums%5Bi%5D) %7B%0A        %09%09isRepeat = false;%0A        %09%09nums%5B++i%5D = nums%5Bj%5D;%0A        %09%7D else %7B%0A        %09%09if(!isRepeat) %7B%0A        %09%09%09isRepeat = true;%0A
         
   nu
@@ -866,29 +866,31 @@
     
-  
+%09%09%09
 nums%5B
-cur
 ++
+i
 %5D = n
-ow; 
+ums%5Bj%5D;
 %0A   
@@ -890,28 +890,26 @@
 j%5D;%0A        
-    
+%09%09
 %7D%0A          
@@ -910,18 +910,10 @@
     
-    i = j;
+%09%7D
 %0A   
@@ -938,11 +938,13 @@
 urn 
-cur
+i + 1
 ;%0A  

update solution