80. 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].
---
public class Solution { public int removeDuplicates(int[] A) { if(A.length <= 2) return A.length; int i=1, j=1; int count=1; while(j < A.length){ if(A[j] == A[j-1]){ // dup if(count<2){ if(i != j) A[i] = A[j]; i++; count++; } }else{ // copy to avaible place if(i != j) A[i] = A[j]; i++; count = 1; } j++; } return i; // new length } }
浙公网安备 33010602011771号