Given a sorted array, delete the repeating number in the original array so that each element appears only once and returns the length of the new array.
Do not use additional array space and must be done without additional space in place.
Sample Example
To array a =[1,1,2], your function should return a length of 2, at which time a=[up].
This simple difficulty of the problem to train to the first time to think of solutions, first an ugly solution
1 intRemoveDuplicates (vector<int> &nums) {2 //Write your code here3 if(Nums.empty ()) {4 return 0;5 }6vector<int>::iterator it=Nums.begin ();7vector<int>:: iterator temp;8it++;9 intmark=nums[0];Ten while(it!=Nums.end ()) { One if(*it==Mark) { Atemp=it; -it=nums.erase (temp); - } the Else{ -mark=*it; -it++; - } + } - returnnums.size (); +}
Two pointers one after the other, if back and before, after deletion, and move backward one bit.
At least this is the first to think, the following post a beautiful
1 intRemoveDuplicates (vector<int> &nums) { 2 if(Nums.empty ())return 0; 3 intCount=0; 4 for(intI=1; I<nums.size (); i++){ 5 if(nums[i]!=Nums[count]) { 6count++;7nums[count]=Nums[i]; 8 } 9 } TenNums.resize (count+1); One returncount+1; A}
The array within the count+1 is the result, the number of >=count is overwritten into count, and then the excess is removed.
100. Delete duplicate numbers in the sorted array