# 80. Remove Duplicates from Sorted Array II

**<font color=red>难度: Medium</font>**

## 刷题内容

> 原题连接

* https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii

> 内容描述

```
Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at most twice and return the new length.

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

Example 1:

Given 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 respectively.

It doesn't matter what you leave beyond the returned length.

Example 2:

Given nums = [0,0,1,1,1,1,2,3,3],

Your function should return length = 7, with the first seven elements of nums being modified to 0, 0, 1, 1, 2, 3 and 3 respectively.

It doesn't matter what values are set beyond the returned length.
```

## 解题方案

> 思路 1
******- 时间复杂度: O(N^2)******- 空间复杂度: O(1)******

通过Remove Duplicates from Sorted Array I的解法进行修改。如果从当前位置开始，连续三位值相等就pop掉当前值。

beats 91.64%

```python
class Solution(object):
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if not nums:
            return 0
        if len(nums) <= 2:
            return len(nums)
        idx = 0
        while idx < len(nums) - 2:
            if nums[idx] == nums[idx+1] == nums[idx+2]:
                nums.pop(idx)
            else:
                idx += 1
        return len(nums)
```


> 思路 2
******- 时间复杂度: O(N)******- 空间复杂度: O(1)******

我想看程序更能解释这个算法，参考[智慧巅峰](https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/discuss/27976/3-6-easy-lines-C++-Java-Python-Ruby)

``` 
Just go through the numbers and include those in the result that haven't been included twice already.
```

beats 91.64%

```python
class Solution(object):
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        idx = 0
        for num in nums:
            if idx < 2 or num > nums[idx-2]:
                nums[idx] = num
                idx += 1
        return idx
```
