[lintcode easy]Remove Duplicates from Sorted Array II

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].

 

///using two pointer to track the int array.

///The first one point to the end of the return array

///The second pointer keep tracking current array

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

 

posted on 2015-11-25 02:49  一心一念  阅读(134)  评论(0编辑  收藏  举报

导航