刷题顺序:https://blog.csdn.net/IBelieve2016/article/details/104544763
/*
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 A = [1,1,2],
Your function should return length = 2, and A is now [1,2].
*/
#include <iostream>
#include <vector>
using namespace std;
int solution(vector<int> &nums){
int res=0;//统计结果
int k=0;//重复数计数
if(nums.size()==1) return 1;
for(int i=0;i<nums.size();i++){
//边遍历,边移动位置
nums[i-k]=nums[i];
//
if(nums[i]==nums[i+1]){
//相同则统计重复数
k++;
}else{
//不同则统计不同数
res++;
}
}
cout<<"K:"<<k<<endl;
nums.erase(nums.end()-k,nums.end());
return res;
}
int main(){
vector<int> nums{0,0,1,1,1,2,2,3,3,4};
cout<<solution(nums)<<endl;
for(int i=0;i<nums.size();i++){
cout<<nums[i];
}
cout<<endl;
return 0;
}