2014年2月12日星期三

LeetCoder - Remove Duplicates from Sorted Array II

 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==null) {
            return 0;
        }
        if(A.length<=2) {
            return A.length;
        }
        int p1 = 0;
        for(int p2=0;p2<A.length;p2++) {
            if(p2+2>=A.length || !(A[p2]== A[p2+1] && A[p2]==A[p2+2]) ) {
                A[p1++] = A[p2];
            }
        }
        return p1;
    }
}

没有评论:

发表评论