wayetan
12/27/2013 - 8:38 AM

Remove Duplicates from Sorted Array

Remove Duplicates from Sorted Array

/**
 * 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) {
        int len = A.length;
        int count = 1;
        int i = 0;
        if(len <= 2)
            return len;
        for(int j = 1; j < len; j++){
            if(A[j] == A[i]){
                // count the difference
                if(count < 2){
                    count++;
                    A[++i] = A[j]; 
                }
            } else {
                count = 1;
                A[++i] = A[j];
            }
        }
        return i + 1;
    }
    
    //better one:
    public int removeDuplicates(int[] nums) {
        int len = nums.length;
        if(len < 3) return len;
        int i = 1;
        for(int j = 2; j < len; j++) {
            if(nums[j] != nums[i] || nums[j] != nums[i - 1])
                nums[++i] = nums[j];
        }
        return i + 1;
    }
}
/**
 * Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.
 * Do not allocate extra space for another array, you must do this in place with constant memory.
 * For example,
 * Given input array A = [1,1,2],
 * Your function should return length = 2, and A is now [1,2].
 */
 
public class Solution {
    public int removeDuplicates(int[] A) {
        int len = A.length;
        int i = 0;
        if(len <= 1) 
            return len;
        for(int j = 1; j < len; j++){
            if(A[j] != A[i])
                A[++i] = A[j];
        }
        return i + 1;
    }
}