> For the complete documentation index, see [llms.txt](https://protegejj.gitbook.io/algorithm-practice/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://protegejj.gitbook.io/algorithm-practice/leetcode/two-pointers/80-remove-duplicates-from-sorted-array-ii.md).

# 80 Remove Duplicates from Sorted Array II

## 80. [Remove Duplicates from Sorted Array II](https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/description/)

## 1. Question

Follow up for "Remove Duplicates":\
What if duplicates are allowed at mosttwice?

For example,\
Given sorted arraynums=`[1,1,1,2,2,3]`,

Your function should return length =`5`, with the first five elements ofnumsbeing`1`,`1`,`2`,`2`and`3`. It doesn't matter what you leave beyond the new length.

## 2. Implementation

```java
class Solution {
    public int removeDuplicates(int[] nums) {
        if (nums.length <= 2) {
            return nums.length;
        }

        int count = 1, index = 1;

        for (int i = 1; i < nums.length; i++) {
            if (nums[i - 1] != nums[i]) {
                count = 1;
                nums[index++] = nums[i];
            }
            else if (count < 2) {
                nums[index++] = nums[i];
                ++count;
            }
        }
        return index;
    }
}
```

## 3. Time & Space Complexity

时间复杂度O(n), 空间复杂度O(1)
