面试经典 150 题 (四)

向前移动元素需要k的值,所以移动需要放在最后面。
class Solution {
    public int removeDuplicates(int[] nums) {
        if (nums.length < 1) return 0;
        int curNum = nums[0];
        int k = 0;
        int count = 0;
        int i;
        for (i = 0; i < nums.length; i++){
            if (curNum == nums[i])
                count++;
            else{
                if (count > 2){
                    k = k +  count - 2;
                }
                curNum = nums[i];
                count = 1;
            }
            nums[i - k] = nums[i];
        }
        if (count > 2){
            return i - k - (count - 2);
        }
        return i - k;
    }
}
                    
                
                
            
        
浙公网安备 33010602011771号