Because the test instructions of this topic is to require us to operate on the original array, the operation becomes slightly more complicated, otherwise the direct use of map is the simplest.
The basic idea is to record two pointers, one is the current array, the other is the destination array, and note that if more than 2 repetitions are found, then the cur of the destination array will be blocked,
Until a different occurrence and then assign a value forward.
Class Solution {public: int removeduplicates (vector<int>& nums) { if (nums.size () ==0) return 0; int cur=1; Modified after array of the lower punctuation int sum=0,temp; for (int i=1;i<nums.size (); i++) { temp=nums[i]; if (Nums[i]==nums[i-1]) { sum++; if (sum<2) {nums[cur]=temp; cur++; } } else { sum=0; Nums[cur]=temp; cur++; } } return cur;} ;
There is an online solution, initially did not think, and later found that forgot to see the conditions---> array has been sequenced, so only judge Nums[i] and nums[i-2] is feasible.
If i sweep to the current element before index already exists two (note, because a is orderly, so only need to judge the first two lines), then I keep moving. Otherwise , the element I points to is added to index,index and i Move forward together.
Class Solution {public: int removeduplicates (int a[], int n) { if (n < 3) return n; int index = 2; for (int i = 2; i < n; i + +) { if (a[i]! = a[index-2]) A[index + +] = A[i]; } return index; };
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
[Leetcode] Remove duplicates from Sorted array II (array subscript operation)