[LeetCode-JAVA] 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,1,2,2,3],

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

 

思路:记录每个数字的次数,并且维护新数组的位置。

 

public class Solution {
    public int removeDuplicates(int[] nums) {
        if(nums.length == 0)
            return 0;
            
        int walker = 1; //每个的数量
        int count = 1; //总类数量
        int loc = 1; //定位

        for(int i = 1 ; i < nums.length ; i++){            
            if(nums[i] == nums[i-1]){
                if(walker < 2){
                    walker++;
                    count++;
                }else{    //出现次数大于2次
                    walker++;
                    continue;
                }
            }else{
                    walker = 1;    //出现新数字
                    count++;
            }
            nums[loc] = nums[i];
            loc++;
        }
        
        return count;
    }
}

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。