給定一個已排序的數組,刪除重復的元素,這樣每個元素只出現一次,並且返回新的數組長度。
不允許為另一個數組使用額外的空間,你必須就地以常量空間執行這個操作。
例如,
給定輸入數組為 [1,1,2]
你的函數應該返回length = 2, 其前兩個元素分別是1和2。它不關心你離開後的新長度。
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& nums) {
if (nums.begin() == nums.end()) return 0;
vector::iterator itor;
for (itor = nums.begin(); itor != nums.end() && itor + 1 != nums.end(); ++itor) {
while (*itor == *(itor + 1)) {
nums.erase(itor + 1);
if (itor + 1 == nums.end())
break;
}
}
return nums.size();
}
};