删除排序数组中的重复数字 II

跟进“删除重复数字”:

如果可以允许出现两次重复将如何处理?

样例

给出数组A =[1,1,1,2,2,3],你的函数应该返回长度5,此时A=[1,1,2,2,3]

解题思路:基本思路和上一道题的删除排序数组中的重复数字差不多,不过需要一个额外的变量time来标记出现的次数。

public class Solution {
    /**
     * @param A: a array of integers
     * @return : return an integer
     */
    public int removeDuplicates(int[] nums) {
        // write your code here
        int len = nums.length;
        int count=0;
        int sum=1;
        if(len==0) return 0;
        if(len<3)  return len;
        int time = 1 ;
         for(int i=1;i<len;i++){
            if(nums[count]!=nums[i]){
                count++;
                nums[count]=nums[i];
                time = 1;
            }else if(nums[count]==nums[i]){
                if(time<2){
                    count++;
                    time++;
                    nums[count]=nums[i];
                }
            }
        }
        return count+1;
    }
}
原文地址:https://www.cnblogs.com/wangnanabuaa/p/4990247.html