Remove Duplicates from Sorted Array II

来源:互联网 发布:天使与魔鬼 知乎 编辑:程序博客网 时间:2024/06/01 20:20

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


  Better Approach
    Key to solve:
    start from index: prev=1; curr=2 since allow twice duplication;
    There are comparison cases:
    1:Only twice duplication allow: compare with two prior elements:
    2. Not accepted case.

Check coding in detail below

public class Solution {    public int removeDuplicates(int[] A) {        int len=A.length;        if(len<3) return len;        int prev=1;        int cur=2;        while(cur<len){            //accepted case            if(A[cur]==A[prev] && A[cur]==A[prev-1]){                cur++;            }else{  //unaccepted case                prev++;                A[prev]=A[cur];                cur++;            }        }        return prev+1;    }}


0 0
原创粉丝点击