弟中弟的Leetcode总结——数组类(五)
题目描述
Remove Duplicates from Sorted Array
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.
Example 1:
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 returned length.
Example 2:
Given nums = [0,0,1,1,1,2,2,3,3,4],
Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively.
It doesn’t matter what values are set beyond the returned length.
思路
题目下了死命令,不允许再给别的数组分配内存,也就是说不能建立新的数组,所以只能在给出的数组上做文章。
只要考虑到相同数合并的方法即可,同时要注意随时改变整个数组的长度,并且遍历到最后的时候需要判断。题目比较简单,所以直接看代码。
代码(C)
int removeDuplicates(int* nums, int numsSize) {
//count用来计算不重复的数的个数
int i = 0, count = 0;
for(i=0;i<numsSize;i++){
//如果最后一个数不是重复的,那么count++
if(i==numsSize-1){
count++;
return count;
}
//如果有重复的
if(nums[i]==nums[i+1]){
count++;
int k = i;
//找到所有重复的值
while(nums[k]==nums[k+1]&&k<numsSize){
k++;
}
//如果遍历到了最后,那么直接输出个数
if(k==numsSize-1){
return count;
}
//j是后面的第一个和前面不同的数的下标
int j = k + 1;
int s = k;
//k回到第一个重复的数的下标
k=i+1;
//进行移动
for(;j<numsSize;j++){
nums[k]=nums[j];
k++;
}
//同时改变数组长度
numsSize-=s - i;
}
//如果不重复,直接count++
else count++;
}
return count;
}