lintcode-easy-Remove Duplicates from Sorted Array

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.

Given input array A = [1,1,2],

Your function should return length = 2, and A is now [1,2].

 

public class Solution {
    /**
     * @param A: a array of integers
     * @return : return an integer
     */
    public int removeDuplicates(int[] nums) {
        // write your code here
        
        if(nums == null)
            return 0;
        if(nums.length <= 1)
            return nums.length;
        
        int i = 0;
        int j = 1;
        
        while(j < nums.length){
            while(j < nums.length && nums[j] == nums[i])
                j++;
            
            if(j < nums.length){
                i++;
                nums[i] = nums[j];
            }
        }
        
        return i + 1;
    }
}

 

posted @ 2016-03-06 07:47  哥布林工程师  阅读(111)  评论(0编辑  收藏  举报