【数组】80. 删除排序数组中的重复项 II
题目:

解答:

1 class Solution { 2 public: 3 int removeDuplicates(vector<int>& nums) 4 { 5 if (nums.size() <= 2) 6 { 7 return nums.size(); 8 } 9 10 // Initialize the counter and the second pointer. 11 int j = 1; 12 int count = 1; 13 14 // Start from the second element of the array and process 15 // elements one by one. 16 for (int i = 1; i < nums.size(); i++) 17 { 18 // If the current element is a duplicate, increment the count. 19 if (nums[i] == nums[i - 1]) 20 { 21 count++; 22 } 23 else 24 { 25 // Reset the count since we encountered a different element 26 // than the previous one. 27 count = 1; 28 } 29 30 // For a count <= 2, we copy the element over thus 31 // overwriting the element at index "j" in the array 32 if (count <= 2) 33 { 34 nums[j++] = nums[i]; 35 } 36 } 37 return j; 38 } 39 };

浙公网安备 33010602011771号