Title: Give a sorted array, remove duplicate elements in the array and allow up to two elements of the same, and finally return the processed array length, and the array is collated.
Algorithm idea: When the array length is less than 3 o'clock do not tidy up the array, directly return the length of the array; When the array length is greater than or equal to 3 o'clock, with the pre record of the precursor element, the flag tag repeats once, p records the end coordinates of the new array, and then scans the entire array, adjacent to two elements, if identical and flag= 0 The elements of the comparison are put into the new array, flag=1, and conversely, if the magnitude element is the same then continue, if not the same, put the comparison element into the new array flag=0.
The code is as follows:
Class Solution {public: int removeduplicates (int a[], int n) { int p;//record end of new array int pre;//forward variable int flag ;//Mark element repeats several times if (n==0| | n==1| | n==2) { return n; } else{ pre=a[0]; flag=0; P=1; for (int i=1;i<n;i++) { if (pre==a[i]&&!flag) { a[p++]=a[i]; flag=1; } else{ if (pre==a[i]) continue; else{ Pre=a[i]; A[p++]=a[i]; flag=0 ; }}} return p;}} ;
Leetcode Remove duplicates from Sorted Array II