C语言
int removeDuplicates(int* nums, int numsSize){
int i,j;
//利用双指针
if(numsSize == 0)
return numsSize;
for(i=0,j=1;j<numsSize;j++){
if(nums[i]!=nums[j])
nums[++i]=nums[j];
}
return numsSize = i+1;
}
C++
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int size = nums.size();
int cnt = 0; //统计当前元素需要前移的位数,注意还是计数排序思想
for(int i=1; i<size; ++i){
if(nums[i] == nums[i-1])
cnt++;
nums[i-cnt] = nums[i]; //前移cnt个位置
}
return size-cnt;
}
};
python
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
if not nums: return 0
i = 0
for j in range(1, len(nums)):
if nums[i] != nums[j]:
i += 1
nums[i] = nums[j]
return i + 1