26 Remove Duplicates from Sorted Array
Given input array nums = [1,1,2],
Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.
It doesn't matter what you leave beyond the new length.Naive Approach
int removeDuplicates(vector<int>& nums) {
if (nums.empty()) return 0;
else if (nums.size() == 1) return 1;
for (int i = 1; i < nums.size(); i++) {
if (nums.at(i - 1) == nums.at(i)) {
nums.erase(nums.begin() + i);
i--;
}
}
return nums.size();
}Optimal Approach
Last updated