leetcode 80 Remove Duplicates from Sorted Array II ----- java

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.

是第26题的延伸版,26题说的是给一个排序好的数组,然后删掉所有重复的数字,使所有数字只出现1次,然后返回长度。

这道题指的是允许数字最多出现2次。然后求长度len2。并且返回的数组前len2个数应当是整理过之后的数组。

public class Solution {
    public int removeDuplicates(int[] nums) {

        int len = nums.length;
        if( len < 2 )
            return len;
        int flag = nums[0];
        int times = 1;
        int res = len;
        for( int i = 1 , j = 1;i<len;i++){
            if( flag == nums[i] ){
                if( times == 1)
                    times++;
                else{
                    res--;
                    continue;
                }
            }else{
                flag = nums[i];
                times = 1;
            }
            nums[j] = nums[i];
            j++;
        }
        
        return res;
    }
}
原文地址:https://www.cnblogs.com/xiaoba1203/p/5967229.html