您的位置:首页 > 其它

leetcode (26) - Remove Duplicates from Sorted Array

2016-11-13 13:59 639 查看
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) {
if(numsSize==0) return 0;

int length=1, flag=0;
int tmp=nums[0], start=0, i=start+1;

while(i<numsSize){

while(i<numsSize && nums[start] == nums[i]){ // i指向第一个不等于start的位置
i++;
}

if(i != numsSize){ // 如果i没有走到最后
if (i==start+1) { //没有找到有相同的

start=i;
i++;

} else { //找到相同的了

nums[start+1]=nums[i];
start=start+1;
i++;
}
} else { // 如果i走到最后
if(i==start+1){
break;
} else { //找到相同的
nums[start+1]=nums[i-1];
}
}
}

return start+1;

}
*/

int removeDuplicates(int* nums, int numsSize) {
if(numsSize==0) return 0;
int first=0, second=1;
while(second < numsSize){
if(nums[second] == nums[second-1]){ // second找到第一个不等于firstd的位置
second++;
continue;
}

nums[++first]=nums[second++];
}

return first+1;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: