LeetCode Online Judge 题目C# 练习 - 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].
1 public static int RemoveDuplicatesfromSortedArrayII(int[] A) 2 { 3 int prev = A[0]; 4 int numtoremove = 0; 5 int ret = A.Length; 6 7 for (int i = 1; i < ret; i++) 8 { 9 if (prev == A[i]) 10 { 11 numtoremove++; 12 } 13 else 14 { 15 if (numtoremove > 1) 16 { 17 RemoveDuplicatesfromSortedArrayShiftLeft(A, ret, i, numtoremove - 1); 18 ret -= numtoremove - 1; 19 i -= numtoremove - 1; 20 } 21 prev = A[i]; 22 numtoremove = 0; 23 } 24 } 25 26 if (numtoremove > 1) 27 { 28 ret -= numtoremove - 1; 29 } 30 31 return ret; 32 } 33 34 public static void RemoveDuplicatesfromSortedArrayShiftLeft(int[] A, int alength, int index, int n) 35 { 36 for (int i = index; i < alength; i++) 37 { 38 A[i - n] = A[i]; 39 } 40 }
代码分析:
也不难,少remove一个而已,但是要记得 prev = A[i], numtoremove = 0 在下一个不重复处就都需要做。 同样不能忘了最后一个数重复的corner case。