1.题目:
给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度。
(不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成)
Given a sorted array nums, 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.)
2.代码:
int removeDuplicates(int* nums, int numsSize) {
if(numsSize==0)f
return 0;
int p1=0,p2=1;
//第p2和p1一样吗,一样p2++,不一样p2放到p1+1的位置
while(p2<numsSize){
if(nums[p1]==nums[p2])
p2++;
else
nums[++p1]=nums[p2++];
}
return p1+1; //数组长度需+1
// int p1=0,p2=0,pre=-8888;
// while(p2<numsSize){
// if(nums[p2]!=pre){
// pre=nums[p2];
// nums[p1++]=nums[p2++];
// }
// else{
// p2++;
// }
// return p1;
}
3.知识点:
双指针