题目内容:
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.
代码如下:
(一)
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int size = nums.size();
if(size == 0)
return 0;
int size_remove = 1;
int i = 1;
int j = 0;
while (i < size)
{
if(nums[j] == nums[i])
{
i++;
}
else
{
size_remove++;
j++;
nums[j] = nums[i];
i++;
}
}
return size_remove;
}
};
(二)
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
vector<int> :: iterator vit = unique(nums.begin(),nums.end());
int size = 0;
for(vector<int> :: iterator vit2 = nums.begin();vit2 != vit; vit2++)
{
size++;
}
return size;
};
(三)
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
return removeDuplicates(nums.begin(),nums.end(),nums.begin()) - nums.begin();
}
template <class Tit>
Tit removeDuplicates(Tit first,Tit last,Tit output)
{
while(first != last)
{
*output++ = *first;
first = upper_bound(first,last,*first);
}
return output;
}
};