Leetcode 283. 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,numsshould be[1, 3, 12, 0, 0].
Note:
You must do this in-place without making a copy of the array.
Minimize the total number of operations.

My solution:

后記:2019.5.11
再看當年的筆記,有幾點體會,特記錄一下:

  1. 當年還不知道Two pointer的套路,寫出的代碼有夠暴力,居然循環嵌套循環。再不濟也應該用個ArrayList記錄一下非零的元素,再復制回原數組?
  2. 當年代碼的style有點問題,操作符和變量之間沒有空格。
  3. 當年并沒有寫一些文字解釋自己的代碼或者別人的解法,或者在code中加入注釋。這樣其實不利于自己深入理解代碼,日后看起來也比較費力。自己以后需要多注意啊。
public class Solution {
    public void moveZeroes(int[] nums) {
        int counter = 0;
        for(int i=0; i<nums.length-1; i++) {
            if (nums[i] == 0) {
                counter++;
            }
        }
        while(counter>0){
            for(int i=0; i<nums.length-1; i++) {
                if (nums[i] == 0) {
                    nums[i] = nums[i+1];
                    nums[i+1] = 0;
                }
            }
            counter--;
        }
    }
}

我的解法效率很低,只有3.5%

附一個高明的 code。
下面是我自己對code的理解(2019.05.11)
這個解法其實是利用了Two pointers的套路。

  1. index 指針的物理意義是其左邊的元素為非零的元素。
  2. 第一個循環結束后,所有的非零元素都被放到了index左邊。第二個循環將index到數組末端的元素設置為零即可。
public class Solution { 
     public void moveZeroes(int[] nums) { 
        int index = 0; 
        for(int i = 0; i < nums.length; i++) { 
              if(nums[i] != 0){ 
                    nums[index++] = nums[i]; 
              } 
        } 
        for(int i = index; i < nums.length; i++) { 
            nums[i] = 0; 
        } 
    }
}

效率是87.33%, unbelievable.

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 背景 一年多以前我在知乎上答了有關LeetCode的問題, 分享了一些自己做題目的經驗。 張土汪:刷leetcod...
    土汪閱讀 12,779評論 0 33
  • Question 把數組所有的值為0的元素移到末尾 Given an array nums, write a fu...
    Sinexs閱讀 1,057評論 0 1
  • 每天早上,睜開睡眼惺忪的眼睛,第一件事情就是拿起手機看一下時間,如果不出意外,生物鐘肯定是在6:40左右醒來。起...
    甜葡萄酸葡萄閱讀 232評論 1 1
  • 20170806拖延癥治療之三:化整為零 善用拖延 孩子是我們最好的老師——切土豆! 孩子來到這個世界的目的,何嘗...
    阿小杜閱讀 245評論 0 0