Remove Duplicates from Sorted Array II

来源:互联网 发布:怎么有效瘦脸 知乎 编辑:程序博客网 时间:2024/06/08 18:42

Q:

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].


Solution:

j is the tail of the sub array.

public class Solution {    public int removeDuplicates(int[] A) {        if (A.length < 3)            return A.length;        int j = 1;        int dup = 1;                for (int i = 1; i < A.length; i++) {            if (A[i-1] == A[i]) {                if (dup < 2) {                    dup++;                    A[j] = A[i];                    j++;                }                else                    continue;            }            else {                if (dup >= 2) {                    A[j] = A[i];                    dup = 1;                    j++;                }                else {                    A[j] = A[i];                    j++;                }            }        }        if (j < A.length) {            A[j] = '\0';        }        return j;    }}


0 0
原创粉丝点击