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.
两种方法:
int removeDuplicates(int* nums, int numsSize)
{
/*
int i = 0;
int j = 0;
for(j = 0; j < numsSize ; j ++){
if (j + 1 < numsSize && nums[j] != nums[j + 1]){
nums[i] = nums[j];
i ++;
}
else if(j + 1 == numsSize){
nums[i] = nums[j];
i ++;
}
}
return i;*/
if (numsSize == 0) return 0;
int i = 0;
int j ;
for (j = 1; j < numsSize; j++) {
if (nums[j] != nums[i]) {
i++;
nums[i] = nums[j];
}
}
return i + 1;
}
注:两个索引,一个用于访问,一个用于新生成的数组索引

本文介绍了一种不使用额外空间的方法来去除已排序数组中的重复元素,并保持原地修改,最终返回不含重复项的新长度。提供了两种实现思路及代码示例。
1093

被折叠的 条评论
为什么被折叠?



