个人记录-LeetCode 80. Remove Duplicates from Sorted Array II

问题:
Follow up for “Remove Duplicates”:
What if duplicates are allowed at most twice?

For example,
Given sorted array nums = [1,1,2,3],

Your function should return length = 5,with the first five elements of nums being 1,2 and 3. It doesn’t matter what you leave beyond the new length.

这个问题相对而言比较简单,在纸上画1下处理进程便可。

代码示例:

public class Solution {
    public int removeDuplicates(int[] nums) {
        if (nums == null || nums.length < 1) {
            return 0;
        }

        int begin = 0;
        int end = 1;

        //记录同1个字符重复的次数
        int count = 1;

        while (end < nums.length) {
            //end与begin对应数1致时
            if (nums[end] == nums[begin]) {
                //更新count
                ++count;

                //count <= 2时,将end移动到begin后1个位置,同时增加begin
                //否则,数量过量,不移动begin,直到找到下1个不1样的数
                if (count <= 2) {
                    nums[begin+1] = nums[end];
                    ++begin;
                }
            } else {
                //找到不1样的数,将end移动到begin后1个位置,同时增加begin
                count = 1;
                nums[begin+1] = nums[end];
                ++begin;
            }
            ++end;
        }

        return begin+1;
    }
}

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...