2014年5月10日星期六

Loop Solution - Remove Duplicates from Sorted Array II - backtrack and loop

The idea is to loop through the array, if one element appear more than twice, then mark it as candidate for next eligible element, replace it. The array was changed after one loop since the solution below replacing instead  of swapping.

public class Solution {
    public int removeDuplicates(int[] A) {
        if(A.length < 3) return A.length;
    int i = 1;
    int cur = 1;
    for(int j = 1; j < A.length; j++){
        if(A[j] == A[j-1]){
            cur++;
        }else{
            cur = 1;
        }
        if(cur <= 2){
            A[i] = A[j];
            i++;
        }
    }
    return i;
    }
}

没有评论: