[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;
    }
}

 

你可能感兴趣的:(LeetCode)