题目原型:
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].
基本思路:
遍历数组,当出现某个数与前面连续的数不相等时就开始移位,或者出现第二个连续的数时也开始移位,index表示要插入的位置,就是后面的数移过来的位置。
public int removeDuplicates1(int[] A)
{
if (A.length == 0)
return 0;
int newLen = A.length;//新的数组长度
int index = 0;//要插入的位置
int temp = A[0];
int count = 1;// 计数次数
boolean isFirst = true;
//当出现某个数与前面连续的数不相等时就开始移位,或者出现第二个连续的数时也开始移位,index表示要插入的位置,就是后面的数移过来的位置
for (int i = 1; i < A.length; i++)
{
if (A[i] == temp)
{
count++;
if (count > 2)
{
newLen--;
}
else
{
if (isFirst == true)
{
index = i;
isFirst = false;
}
else
{
if (index + 1 < i)
A[++index] = A[i];// 注意这里是先加后赋值
else //假如相等的话就改变插入位置
index++;
}
}
}
else
{
temp = A[i];
if (index + 1 < i)
A[++index] = A[i];// 注意这里是先加后赋值
else
index++;
count = 1;
}
}
System.out.println(newLen);
for (int i = 0; i <= newLen - 1; i++)
{
System.out.print(A[i] + " ");
}
System.out.println();
return newLen;
}
Remove Duplicates from Sorted Array II,布布扣,bubuko.com
Remove Duplicates from Sorted Array II
原文:http://blog.csdn.net/cow__sky/article/details/20905295