101 · Remove Duplicates from Sorted Array II - LintCode

# Description

Given a sorted array, remove the duplicates in place such that each element appear at most twice and return the new length.
If a number appears more than two times, then keep the number appears twice in array after remove.

Example 1:

Input:

array = []

Output:

0

Explanation:

Empty array, length is 0.

Example 2:

Input:

array = [1,1,1,2,2,3]

Output:

5

Explanation:

the length is 5: [1,1,2,2,3]

# Solution

public class Solution {
    /**
     * @param A: a array of integers
     * @return : return an integer
     */
    public int removeDuplicates(int[] nums) {
        if (nums == null || nums.length == 0){
            return 0;
        }
        int count = 1;
        int left = 0;
        for (int cur = 1; cur < nums.length; cur++){
            if (nums[cur] == nums[cur - 1]){
                if (count < 2){
                    nums[++left] = nums[cur];
                    count++;
                } 
            } else {
                left++;
                nums[left] = nums[cur];
                count = 1;
            }
        }
        return left + 1;
    }
}