remove duplicates from sorted array

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.

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.

说明:

给定一个排序好的数组,去除数组中的重复元素,返回去重后的数组长度,不能构造新的数组。

思路:

定义两个值,分别为长度和上一次遍历的值,当当前元素不等于上一次的值时,长度+1。这个思路时错误的,因为结果不光是判断不重复的数组长度,而是仍然会判断数组中的元素,所以仍然需要对数组的中的元素进行处理。换一个思路,题目中说去重后剩下的元素在数组中也没关系,所以可以尝试在遍历的过程中,后一个元素比当前元素大,就交换位置。

代码一(16ms):

public class Solution {
    public int removeDuplicates(int[] nums) {
        int i = nums.length > 0 ? 1 : 0;
        for (int n : nums)
            if (n > nums[i-1])
                nums[i++] = n;
        return i;
    }
}