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.
class Solution {
public:
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))
it = nums.erase(it);
else
it++;
}
return nums.size();
}
};
本文介绍了一个C++程序,用于在不使用额外空间的情况下从已排序数组中移除重复元素,并返回处理后数组的新长度。该算法通过迭代遍历并利用STL容器erase方法实现原地删除重复项。
579

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



