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,790评论 0 33
  • Question 把数组所有的值为0的元素移到末尾 Given an array nums, write a fu...
    Sinexs阅读 1,059评论 0 1
  • 每天早上,睁开睡眼惺忪的眼睛,第一件事情就是拿起手机看一下时间,如果不出意外,生物钟肯定是在6:40左右醒来。起...
    甜葡萄酸葡萄阅读 240评论 1 1
  • 20170806拖延症治疗之三:化整为零 善用拖延 孩子是我们最好的老师——切土豆! 孩子来到这个世界的目的,何尝...
    阿小杜阅读 320评论 0 0