https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/
Solution 1. Loop through the array, when see a none duplicated number, copy it to location s and s++.
int removeDuplicates(vector<int>& nums) {
if(nums.size()<2) return nums.size();
int s=1;
for(int i=1; i<nums.size(); i++) {
if(nums[i] != nums[i-1]) {
nums[s] = nums[i];
s++;
}
}
nums.erase(nums.begin()+s, nums.end());
return s;
}
Solution 2. Remove when see duplicates. (slow)
int removeDuplicates(vector<int>& nums) {
if(nums.size()<2) return nums.size();
for(vector<int>::iterator it = nums.begin()+1; it<nums.end();) {
if(*it == *(it-1)) nums.erase(it);
else it++;
}
return nums.size();
}
No comments:
Post a Comment