283. Move Zeroes

The tricky part is that the relative order of non-zero values need to be maintained. A straightforward solution:

  • traverse the array to find any non-zero value
  • move the found value from step 1 to the front of the array using a pointer to keep track of index
  • change all the values to zero after the pointer
    public static void moveZeroes2(int[] nums) {
        if (nums == null || nums.length < 2) return;
        int index = 0;
        for (int num : nums){
            if (num != 0){
                nums[index++] = num;
            }
        }
        for (; index < nums.length; index++){
            nums[index] = 0;
        }
        return;
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,768评论 0 33
  • 今天搬回宿舍的第一个夜晚 宿舍里是空荡荡的 落地窗外前几秒还能听见行人的谈话 后几秒能听见天花板上的脚步声 喜欢这...
    弗蔷甸帕阅读 184评论 0 0
  • 删了写,写了又删,纠结了能有10分钟… 这一章看完,感觉有点儿拖沓,也不知道是不是我理解的不够深刻,前后有点矛盾,...
    白大花阅读 193评论 0 0