題目原型:
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;
}