# [80\. Remove Duplicates from Sorted Array II](https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/) :::spoiler Hint ```cpp= class Solution { public: int removeDuplicates(vector<int>& nums) { // Initialize the index to insert the next valid element // Initialize the count of the current element to 1 (the first element is always counted once) // Iterate through the array starting from the second element for () { // If the current element is the same as the previous element, increment the count if () { } else // If the current element is different from the previous element, reset the count to 1 { } // If the count is less than or equal to 2, we can keep this element if () { // Place the current element at the insertIndex and increment insertIndex } } // Return the index where the next element would be inserted, which is the new length of the array } }; ``` ::: :::spoiler Solution ```cpp= class Solution { public: int removeDuplicates(vector<int>& nums) { int insertIndex = 1; int cnt = 1; for (int i = 1; i < nums.size(); ++i) { if (nums[i] == nums[i - 1]) ++cnt; else cnt = 1; if (cnt <= 2) nums[insertIndex++] = nums[i]; } return insertIndex; } }; ``` - 時間複雜度:$O(N)$ - 空間複雜度:$O(1)$ :::