去除重復(fù)元素,即計(jì)算不同元素?cái)?shù)量。
注意點(diǎn):
對(duì)容器進(jìn)行操作時(shí),注意判斷是否為空。
代碼:
int?removeDuplicates(vector<int>& nums) {
? ? if(nums.size()==0)
? ? ? ? return0;
? ? inti=0,lenth=0;
? ? for(intj=1;j
? ? {
? ? ? ? if(nums[i]!=nums[j])
? ? ? ? {
? ? ? ? ? ? i++;
? ? ? ? ? ? nums[i]=nums[j];
? ? ? ? }
? ? }
? ? lenth=i+1;
? ? returnlenth;
}
intmain(intargc,constchar* argv[]) {
? ? // insert code here...
? ? vector<int>nums={0,0,1,2,2,3,4,5,6,6,8,8,9};
? ? cout<<removeDuplicates(nums)<<endl;
? ? return 0;
}