题目要求如下:
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) {
if (n == 0)
return n;
int i = 0;
int j = 0;
bool flag = false;
while (j < n) {
if (A[i] == A[j]) {
flag = false;
++j;
while (A[i] == A[j] && j < n) {
++j;
flag = true;
}
if (flag == true) {
A[++i] = A[j-1];
}
}
else {
A[++i] = A[j];
}
}
return i+1;
}
};
举个简单的例子把:A[5] = {1,1,1,2,3}
1,第一次外层循环:
i = 0, j = 0
A[i] = A[j]
j = 1;
进入内层循环,看看后面有几个值和A[i]相等,只要有,则设为true, j = 3,跳出内层循环
flag = true: A[1] = A[3-1] = 2
2,第二次外层循环
此时i = 1, j = 3
A[1] != A[3]
则把A[3]的值:2赋给A[2]
此时A = {1,1,2,2,3}
3,第三次外层循环:
i = 2,j = 3
j = 4
不进入内层循环
4,第四次外层循环:
i = 2, j = 4
A[3] = 3
5,第五次循环:
j= 5,跳出
返回(i+1)=3
A[3] = {1,1,2,3}