LeetCode - Remove Duplicates from Sorted Array II

来源:互联网 发布:中印军力 知乎 编辑:程序博客网 时间:2024/05/17 22:55

Question:

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 int removeDuplicates(int[] A) {int num = 0;int length = A.length;if (length == 0) {return 0;}int index = 0;for (int i = 1; i < A.length; i++) {if (A[num] == A[i]) {index++;if (index <= 1) {A[++num] = A[i];}}if (A[num] != A[i]) {A[++num] = A[i];index = 0;}}num = num + 1;return num;}


0 0