# C++ solution 32ms

• ``````int removeDuplicates(vector<int>& nums) {
int length = nums.size();
int tw = 1;
int idx = 0;

while(idx < nums.size()-1)
{
int tmp = idx + 1;

while(tmp < nums.size() && nums[tmp] == nums[idx])
{
++tmp;
length--;
}

if(tmp < nums.size() && nums[tmp] != nums[idx])
{
nums[tw] = nums[tmp];
tw++;
idx = tmp;
}
else
break;
}
return length;
}``````

• /*
采用直接赋值的办法，用两个迭代器，一个从头跑到尾，寻找不同的值，一个记录当前不同值赋值的地方。
优点是，思路简单，编程简单；
缺点是，未出现重复值时，依然要赋值一遍，存在冗余；
时间为37ms；
*/

``````class Solution {
``````

public:
int removeDuplicates(vector<int>& nums) {

``````if(nums.size() == 0 || nums.size() == 1)
return nums.size();

int length=1;//长度

vector<int>::iterator cur= nums.begin()+1;

for(vector<int>::iterator itr=nums.begin()+1; itr != nums.end(); itr++)
{
if(*itr != *(itr-1))
{
*cur = *itr;
cur++;
length++;
}
}
return length;
}
``````

};

• you should "remove the duplicates in place such that each element appear only once" .

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.