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

# 80. Remove Duplicates from Sorted Array II

## 1.問題

* 給予一個sorted array, 移除多餘的元素, 每個元素最多出現2次

![](/files/-LNcGPI8p8ELKLks2Zbj)

## 2.想法&#x20;

* 提問:
* function header, parameter
* test input
* 說明想法&#x20;
  * 向前比對
    * 當num\[i] == num\[i - 1]時, 且cnt < 2, 讓 num\[i]加入
    * 當num\[i] != num\[i -1]時, 讓num\[i]加入, 但cnt歸零
* 測試計算複雜度

## 3.程式碼

```
class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        if (nums.size() == 0) {
            return 0;
        }
        int n = nums.size(), cnt = 1, index = 1;
        for (int i = 1; i < n; i++) {
            if (nums[i] == nums[index - 1]) {
                if (cnt < 2) {
                    nums[index++] = nums[i];
                    cnt++;
                }
            } else {
                nums[index++] = nums[i];
                cnt = 1;
            }
        }
        
        return index;
    }
};
```
