Remove Duplicates from Sorted Array II

Leetcode

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 1, 1, 2, 2 and 3. It doesn't matter what you leave beyond the new length.

Subscribe to see which companies asked this question

Analysis

Ref1
和之前的remove duplicates from sorted array I思路一样。用两指针,第一个指针i遍历整个数组,第二个指针index用来存不超过三次的数

Code

public class Solution {
    public int removeDuplicates(int[] nums) {
        if(nums.length<=2) {return nums.length;}
        int index = 1;
        for (int i=2; i<nums.length; i++){
            //IMPORTANT! Check duplicates around nums[index], not nums[i]
            if(nums[i]!=nums[index] || nums[i]!=nums[index-1]){
                index++;
                nums[index]=nums[i];
            }
        }
        return index+1;
    }
}