Remove Duplicates from Sorted Array II
Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?
For example,
Given sorted array A = [1,1,1,2,2,3],
Your function should return length = 5, and A is now [1,1,2,2,3].
class Solution { public: int removeDuplicates(int A[], int n) { // Start typing your C/C++ solution below // DO NOT write int main() function int last = INT_MAX, counter = 0; int pre = 0, i = 0; int new_length = n; for(i = 0; i < new_length; i ++){ if (A[i] != last){ if (counter > 2){ for(int j = i; j < n; j++){ A[j - counter + 2] = A[j]; } new_length -= (counter - 2); i -= (counter - 2); } counter = 1; last = A[i]; }else{ counter++; } } if (counter > 2){ for(int j = i; j < n; j++){ A[j - counter + 2] = A[j]; } new_length -= (counter - 2); } return new_length; } };
浙公网安备 33010602011771号