天天看點

[LeetCode刷題日記] Remove Duplicates from Sorted Array

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() == 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();
    }
};