leetCode 283. Move Zero

    題目鏈接:https://leetcode.com/problems/move-zeroes/

    題目內容:

Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.

For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].

    題目分析:

    題目給出的函數參數是vector<int>的,因此使用了vector的api不可避免,msdn上的vector手冊在此!這道題其實想了挺久的,因爲一看暴力但感覺很low的想法一下子就有了:記錄原有vector的長度len1,然後遍歷的時候遇到0就刪掉,剩下的長度爲len2,最後再vector後面補上(len1-len2)個0.一直沒動手的原因就是覺得這樣無論在時間還是在空間上感覺都很低效。後來想到,多加一個指針或者遊標就可以了啊,讓它記錄不爲0的數的位置,另一個遊標一直往前遍歷,最後再補上0,這裏的補上只要修改值就可以。原來的和優化後的代碼如下,其中,註釋的爲原來的代碼。注意,原來的代碼中每刪掉(erase操作)一個元素,整個vector的長度減1,相應的當前遊標應該回滾到上一個,因爲在循環體內結束一次循環,即”}“之前會修改遊標的值(做”++“操作)

void moveZeroes(vector<int>& nums) {
    /**
     * cost 20ms
    int size = nums.size();
    for(vector<int>::iterator cur = nums.begin(); cur != nums.end(); cur++) {
        if(*cur == 0) {
            nums.erase(cur);
            cur--;
        } else
            continue;
    }
    int cursize = nums.size();
    for(int count = 0; count < size-cursize; count++)
        nums.push_back(0);
    */
    int size = nums.size();
    
    vector<int>::iterator nonZero = nums.begin();
    vector<int>::iterator current = nonZero;
    vector<int>::iterator end = nums.end();
    for(; current != nums.end(); current++) {
        if(*current != 0) {
            *nonZero = *current;
            nonZero++;
        }
    }
    for(; nonZero != end; nonZero++)
        *nonZero = 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章