Remove Duplicates from Sorted Array II

来源:互联网 发布:windows ad与配置 编辑:程序博客网 时间:2024/05/17 00:08

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

定义一个计数器 标记相同数字的个数 超过2则 进行删除  定义一个赋值计数器 标记赋值到第几位 若进行删除操作 则不进行赋值  代码如下:

public class Solution {    public int removeDuplicates(int[] A) {        if(A.length<=2)return A.length;        int com=A[0];        int count=0;        int cur=0;        for(int i=1;i<A.length;i++){            if(A[i]==com){                count++;                if(count<2){                   cur++;                   A[cur]=A[i];                }            }else{                cur++;                A[cur]=A[i];                com=A[i];                count=0;            }            }        return cur+1;    }}


0 0