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]
.
解题思路:
与1类似有一个movesteps来记录i位置需要往前移动几位,另外加一个变量来统计每个不同元素的个数。
Java Code:
public int removeDuplicates(int[] A) { int moveSteps = 0; int count = 1; for(int i = 1; i < A.length; i++){ if(A[i] == A[i-1]){ count++; }else{ if(count > 2) moveSteps += count - 2; count = 1; } if(count <= 2){ A[i-moveSteps] = A[i]; } } if(count > 2) moveSteps += count - 2; return A.length - moveSteps; }
No comments:
Post a Comment