26.Remove Deplicates 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.

For example,
Given input array nums = [1,1,2],

Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn't matter what you leave beyond the new length.

算法:

因为数组已经有序,我们可以维持两个指针i 和 j, 只要nums[i] == nums[j], 就增加j 来跳出循环。

当遇到nums[j] != nums[i], 查重循环结束, 我们必须把nums[j] 的值复制给nums[i+1】,i 然后增加。

重复这一过程直到j 到达数组尾部。

public int removeDuplicates(int[] nums) {
    if (nums.length == 0) return 0;
    int i = 0;
    for (int j = 1; j < nums.length; j++) {
        if (nums[j] != nums[i]) {
            i++;
            nums[i] = nums[j];
        }
    }
    return i + 1;
}

  

posted @ 2017-07-24 23:33  dreamafar  阅读(140)  评论(0编辑  收藏  举报