美文网首页
LeetCode每日一题:remove duplicates f

LeetCode每日一题:remove duplicates f

作者: yoshino | 来源:发表于2017-05-18 16:52 被阅读13次

    问题描述

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

    相关文章

      网友评论

          本文标题:LeetCode每日一题:remove duplicates f

          本文链接:https://www.haomeiwen.com/subject/hrgsxxtx.html