> 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;
    }
};
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://jenhsuan.gitbook.io/algorithm/leetcode/80.-remove-duplicates-from-sorted-array-ii.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
