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.數組
這題其實就是將一個有序數列中重複數字去除,最後返回新數組的長度。
我是用了兩個迭代器來完成這道題目,將第一個迭代器指向數組開頭,第二個迭代器指向第二個數,依次與第一個迭代器比對,若相等就迭代器二就指向下一個數繼續對比,不相等就記錄下第一個迭代器的數,而後將第一個迭代器指向第二個迭代器指向的數。app
這題惟一有個陷阱的地方就是最後新數組的數值,要賦給初始數組,才能經過測試。審題不清的快哭了。。測試
class Solution { public: int removeDuplicates(vector<int>& nums) { if( nums.size() == 0) return 0; vector<int>::iterator one = nums.begin(); vector<int> newNums(1,*one); for( vector<int>::iterator two = nums.begin() + 1; two != nums.end(); ++two){ if( *one != *two ){ one = two; newNums.push_back( *one ); } } nums = newNums; return nums.size(); } };