# Share my clean C++ code

• ``````int count = 0;
for(int i = 1; i < n; i++){
if(A[i] == A[i-1]) count++;
else A[i-count] = A[i];
}
return n-count;``````

• this is best solution I ever found.

• Thank you very much.

• Definitely the best one.

• I think this problem should tell us that it's NOT necessary to delete the duplicate elements. The delete operation costs many time. :(

• fucking awesome!

• why no one erase the unnecessary elements at the tail?

``````int Solution::removeDuplicates(vector<int>& nums) {
int num_duplicates = 0;
for (int i = 1; i < nums.size(); ++i) {
if (nums[i] == nums[i - 1]) {
++num_duplicates;
} else {
nums[i - num_duplicates] = nums[i];
}
}
nums.erase(nums.end() - num_duplicates, nums.end());  // add this line!!!
return nums.size();
}
``````

• @xsh6528 Because it's a waste of time.As the description of this question : It doesn't matter what you leave beyond the new length.

• This post is deleted!

• @jasusy this solution is so much easier to understand than all the other ones.

• @jackyl310 Thanks :)

• Amazing solution.

• @jasusy
If theTwo identical numbers are not adjacent，such as a[6]=｛1，3，1，4，1，4｝，what is the result?

• @Litch said in Share my clean C++ code:

@jasusy
If theTwo identical numbers are not adjacent，such as a[6]=｛1，3，1，4，1，4｝，what is the result?

sorry,i don not see"Given a sorted array"

• I thought this solution is awesome but it still need to erase unnecessary elements at the tail. For example, if the input is {1,2,2,3,4,5,5,6}, the output is {1,2,3,4,5,6,5,6}. Because the final elements still remain, and the following is my solution.

``````int removeDuplicates(vector<int>& nums) {
int count = 0;
int n = nums.size();
vector<int> newNums;
for (int i = 1; i < n; i++) {
if (nums[i] == nums[i - 1])
count++;
else
nums[i - count] = nums[i];
}
for (int i = 0; i < n - count; i++) {
newNums.push_back(nums[i]);
}
//return newNums;
return n - count;
}``````

• This post is deleted!

• This post is deleted!

• ``````	int count = 1;
for (int i = 1; i < ivec.size(); ++i){
if (ivec[i-1]==ivec[i]) continue;
else ++count;
}
return count;
``````