题目:
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 by **modifying the input array in-place with O(1) extra memory.
Example:
Given 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.
分析:
maintain 2个index i 和 j, j > i
i和i的左边的所有元素都是没有duplicates的
从j = i+1开始往右扫描,如果nums[j]不等于nums[i], 那么就找到了一个非duplicate的元素,把这个元素放置在nums[i+1],并且让i自增1.如果nums[j]等于nums[i], 则使j自增1,跳过这个duplicate的元素
public int removeDuplicates(int[] nums) {
if(nums.length <= 1) return nums.length;
int n = nums.length, size = 1, j = 1;
while(j < n) {
if(nums[j] != nums[size - 1]) {
nums[size++] = nums[j];
}
j++;
}
return size;
}