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
}
};
本文介绍三种不同的方法来删除一个已排序数组中的重复元素,并确保每个元素只出现一次。这些方法包括使用迭代器逐个检查元素、设置临时索引来跳过重复项以及利用STL中的distance和unique函数。每种方法都详细展示了如何实现,并提供了时间复杂度和空间复杂度的分析。
1096

被折叠的 条评论
为什么被折叠?



