Remove Duplicates from Sorted Array
Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this in place with constant memory.
For example,
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.
Code 1, Use iterator
ATTENTION PLEASE:
If current element equals to the next, and do something.
// Time Complexity : O(n), Space Complexity : O(1)
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int count = nums.size();
if(nums.empty()) return 0;
for(auto it = nums.begin(); it != nums.end() -1; ){
if(*it == *(it+1)){
nums.erase(it + 1); // erase(pos),pos it iterator; not erase(index)
--count;
}else
++it;//if and only if *it!=*(it+1), execute this line
}
return count;
}
};
Code 2, Use Index
ATTENTION PLEASE:
1. If current element equals to the next, and do something;
2. Set temporary index.
//Time Complexity : O(n), Space Complexity : O(1)
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if(nums.empty()) return 0;
int index = 0;
for(int i = 1; i < nums.size(); ++i){
if(nums[index] != nums[i]){
index += 1;
nums[index] = nums[i];
}
}
return index + 1;
}
};
Code3, Use STL: distance, unique
class Solution {
public:
//Time Complexity : O(n), Space Complexity : O(1)
int removeDuplicates(vector<int>& nums) {
return distance(nums.begin(), unique(nums.begin(), nums.end()) );
// ForwardIterator unique(ForwardIterator beg, ForwardIterator end);
// return the next position of the last non-removed element
}
};