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.size() == 0) return 0; vector ::iterator one = nums.begin(); vector newNums(1,*one); for( vector ::iterator two = nums.begin() + 1; two != nums.end(); ++two){ if( *one != *two ){ one = two; newNums.push_back( *one ); } } nums = newNums; return nums.size(); }};