leetcode 36: 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
if(n<=1) return n;
int i=0;
int j=1;
bool flag = false;
int temp = A[i];
while( j<n) {
if( A[j] != temp) {
i++;
A[i] = temp = A[j];
flag = false;
} else if( flag == false) {
i++;
A[i] = temp = A[j];
flag = true;
}
j++;
}
return i+1;
}
};
浙公网安备 33010602011771号