本文共 869 字,大约阅读时间需要 2 分钟。
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) { Integer prev = null; // last value int count = 0; // number of continuous occurrences of last value int index = 0; // points to index to place next qualified element for (int i = 0; i < A.length; i++) { int candidate = A[i]; if (prev != null && prev == candidate && count == 2) continue; A[index++] = A[i]; // reset count if a new value is encountered if (prev == null || candidate != prev) { prev = candidate; count = 1; } else count++; } return index;}}
转载地址:http://jiuni.baihongyu.com/