LeetCode: 26. 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.
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.
可以理解为把nums中的重复元素删除,假如不同元素一共n个,那么nums[0…n-1]就是新数组,n-1之后的元素我们就不管了。
解决方案
CSDN: Eswai(http://blog.csdn.net/eswai)
方法 1
这里使用了distance和unique函数,算是练习STL知识了:)
// time: O(n) , space: O(1)
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
return distance(nums.begin(),unique(nums.begin(),nums.end()));
}
};
方法 2
// time: O(n) , space: O(1)
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if (nums.empty()) return 0;
int n=1;
for(int i=1;i<nums.size();i++){
// 与前一元素不同的就是新元素,计数加一
if(nums[i]!=nums[i-1]){
// 新元素向前复制
nums[n]=nums[i];
n++;
}
}
return n;
}
};