1. 程式人生 > >Remove Duplicates from Sorted Array II(濾除重複數值,最多保留n個重複值)

Remove Duplicates from Sorted Array II(濾除重複數值,最多保留n個重複值)

/**
 * 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]
 */
// Remove Duplicates from Sorted Array II
// Time complexity: O(n), Space Complexity: O(1)
public class RemoveDuplicatesFromSortedArray2 {
    private static final int len = 2;
    public static int removeDuplicates(int[] arr) {
        if(arr == null) { return 0;}
        if(arr.length <= len) { return arr.length; }
        int index = len;
        for(int i=len; i<arr.length; i++) {
            if (arr[i] != arr[index-len]) {
                arr[index++] = arr[i];
            }
        }
        return index;
    }
    public static void main(String[] arrys) {
        System.out.println("A is [1,1,2,2,2,3,4,4,5]");
        int[] arr = {1,1,2,2,2,3,4,4,5};
        int index = removeDuplicates(arr);
        System.out.println(" length = " + index);
        System.out.print(" A is now:[");
        for(int i=0; i<index; i++) {
            System.out.print(arr[i] + " ");
        }
        System.out.print("]");
    }
}