Leetcode - 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].

Note:
1. You must do this in-place without making a copy of the array.
2. Minimize the total number of operations.

//思路:從左往右,遇到0,則0後面的所有元素往前移動一位,有多少0,移動多少回,最後末尾添加0
void moveZeroes(vector<int>& nums) {
        int count=0;
        for(int i=0;i<nums.size();i++)
            if(nums[i]==0)
                count++;
        int tmp=count;
       for(int i=0; tmp>0 && i<nums.size(); i++){
             if(nums[i]==0){
                  for(int j=i;j<nums.size()-1;j++)
                          nums[j]=nums[j+1];                 
                  tmp--;
                  i--; // in case that start with 00
                } 
        }        
        for(int i=0;i<count;i++)
            nums[nums.size()-1-i]=0;
    }



//別人的做法:

void moveZeroes(vector<int>& nums) {
        int j = 0;
        // move all the nonzero elements advance
        for (int i = 0; i < nums.size(); i++) {
            if (nums[i] != 0) {
                nums[j++] = nums[i];
            }
        }
        for (;j < nums.size(); j++) {
            nums[j] = 0;
        }
    }

刷leetcode的最爽的地方不在於一次次的Accepted,而是自己的絞盡腦汁,想出來自認爲還不錯的代碼,AC後看到討論區裏,大神們更優雅更精緻的代碼後,被虐的那個酸爽。大呼,哎呦臥槽,我怎麼沒想到。。。

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