Move Zeroes

来源:互联网 发布:lg扫地机器人.知乎 编辑:程序博客网 时间:2024/06/10 03:39

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.

类似于那道从数组删除的题

代码:

public void moveZeroes(int[] nums) {        if(nums == null || nums.length == 0) return;        int index = 0;        int count = 0;        for(int i=0;i<nums.length;i++){            if(nums[i] != 0){                nums[index++] = nums[i];            }else{                count++;            }        }        int index2 = nums.length-1;        while(count>0){            nums[index2--] = 0;            count--;        }    }


0 0
原创粉丝点击