Description:
Given a sorted array, remove the duplicates in place such that each element appear onlyonce 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 ofnums being1
and 2
respectively. It doesn't matter what you leave beyond the new length.
解题思路:给定已排序的数组,去除里面重复的元素,返回数组的长度;
解法一:
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if (nums.empty())
return 0;
int idx = 0;
for(int i = 1; i < nums.size(); i ++) {
if (nums[idx] != nums[i])
nums[++idx] = nums[i];
}
return idx + 1;
}
};
代码二:
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
return distance(nums.begin(), unique(nums.begin(), nums.end()));
}
};