> For the complete documentation index, see [llms.txt](https://r24zeng.gitbook.io/leetcode-notebook/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://r24zeng.gitbook.io/leetcode-notebook/wan-quan-an-zhao-jiu-zhang-suan-fa-shua-de-60-dao-zuo-you/ii.-sorted-array/80.-remove-duplicates-from-sorted-array-ii.md).

# 80. Remove Duplicates from Sorted Array II

\# Medium

{% hint style="success" %}
Two pointers work together. One pointer points first element, the other one points third element.
{% endhint %}

### Solution 1:

1. Consider edge cases: less or equal than 2 elements
2. **Remove shouldn't be existed element**
3. Set `p1=0, p2=2`
4. `nums[p1] == nums[p2]` indicates the element is repeated 3 times, then `pop` it
5. `nums[p1] != nums[p2]`, then `p1` and `p2` just move forward one step

### Solution 2(faster):

1. Consider edge cases: less or equal than 2 elements
2. Set count=1, and track last element x
3. **Move should be existed element to correct position**

{% tabs %}
{% tab title="Java O(N)" %}

```java
// Some code
class Solution {
    public int removeDuplicates(int[] nums) {
        int p = 0, count = 0;
        for(int i = 1; i < nums.length; i ++) {
            if(nums[p] == nums[i]) {
                if(count == 0) {
                    count = 1;
                    nums[++p] = nums[i];
                }
            } else {
                count = 0;
                nums[++p] = nums[i];
            }
        }
        
        return p+1;
    }
}
```

{% endtab %}

{% tab title="Java O(N) another way" %}

```java
// Some code
class Solution {
    public int removeDuplicates(int[] nums) {
        int curr = 0, count = 1;
        for(int i = 1; i < nums.length; i ++) {
            if(nums[i] == nums[i-1])
                count ++;
            else
                count = 1;
            
            if(count <= 2)
                nums[++curr] = nums[i];
        }
        
        return curr+1;
    }
}
```

{% endtab %}
{% endtabs %}
