Skip to main content

80. Remove Duplicates from Sorted Array II

Hint

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
}
};
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;
}
};
  • T: O(N)O(N)
  • S: O(1)O(1)