Skip to main content

26. Remove Duplicates from Sorted Array

Hint

class Solution {
public:
int removeDuplicates(vector<int>& nums)
{
// Initialize a counter to keep track of the unique elements' length

// Iterate through the array starting from the second element
for ()
{
// If the current element is different from the previous element
if ()
{
// Assign the current element to the position indicated by cnt and increment cnt
}
}
// Return the count of unique elements in the array
}
};
class Solution {
public:
int removeDuplicates(vector<int>& nums)
{
int cnt = 1;
for (int i = 1; i < nums.size(); ++i)
{
if (nums[i - 1] != nums[i])
{
nums[cnt++] = nums[i];
}
}
return cnt;
}
};
  • T: O(N)O(N)
  • S: O(1)O(1)