Follow up for "Remove duplicates":
What if duplicates is allowed at the most twice?
For example,
Given sorted array nums = [1,1,1,2,2,3]
,
Your function should return length =5
, with the first five elements ofNumsBeing1
,1
,2
,2
and3
. It doesn ' t matter what are you leave beyond the new length.
The idea of solving a problem: Deleting a repeating element in an ordered array, allowing repetition two times and deleting extraneous elements over two times. Method One: Count the elements within two times, and assign the new array to the original array. The code is as follows:
Class Solution {public: int removeduplicates (vector<int>& nums) { if (nums.size () <=2) return Nums.size ();vector<int> num_new; int len=1; int N=1;int begin=nums[0];num_new.push_back (nums[0]), for (int i=1;i<nums.size (); i++) {if (Nums[i]==begin) {if (n <2) {len++;num_new.push_back (nums[i]);} n++;} Else{begin=nums[i];len++;num_new.push_back (Nums[i]); n=1;}} nums=num_new; return len; };
Method Two: Delete in situ
Class Solution {public: int removeduplicates (vector<int>& nums) { if (nums.size () <=2) return Nums.size (); int len=0; int n=0;int begin=nums[0];for (int i=1;i<nums.size ();) {if (* (Nums.begin () +i) ==begin) {n++;if (n>1) { Nums.erase (Nums.begin () +i);} elsei++;} else{begin=* (Nums.begin () +i); i++; n=0;}} return Nums.size (); }};
Method Three: Because it is already well-ordered, repeating elements are together, so we count the number of elements, only the statistics repeat two times the following elements on the line, when repeated two times, that is, the location of the difference is 2, and two values are equal, we do not count. The code is as follows:
Class Solution {public: int removeduplicates (vector<int>& nums) { if (nums.size () <=2) return Nums.size (); int rear=1;for (int i=2;i<nums.size (); i++) {if (!) ( NUMS[I]==NUMS[REAR]&&NUMS[I]==NUMS[REAR-1]) nums[++rear]=nums[i];} return rear+1;} ;
Remove duplicates from Sorted Array II