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, 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的值放在开头。注意,最后要把非零pos后面的值全部置为0

class Solution {
    public void moveZeroes(int[] nums) {
        if(nums == null || nums.length ==0) return;
        int insertPos = 0;
        for(int num:nums){
            if(num!=0) nums[insertPos++] = num;
        }
        while(insertPos<nums.length) nums[insertPos++]=0;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,776评论 0 33
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,934评论 0 23
  • “你于我的存在 就像是打开了令我欢喜的另一个状态 平衡了我骨中叛逆的血液” 至第2745天,暨新婚两周年。 谢谢先...
    野马爱撒野阅读 280评论 0 0
  • 咖啡厅内—— 小A:“你什么时候回来,很多人担心你。” 木心抿了抿手中的摩卡,“他担心吗?” 小A沉默。 木心起身...
    曙教主阅读 266评论 0 1
  • 在中国,20世纪八、九十年代,农村中小学校与村庄毗邻是十分普遍的现象。而且,只要村校相邻,又无围墙间隔,就一定会闹...
    镇南方良金阅读 200评论 0 1