程序员人生 网站导航

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

栏目:php教程时间:2017-03-22 10:08:52

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

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

Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 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;
    }
}
------分隔线----------------------------
------分隔线----------------------------

最新技术推荐