283. Move Zeroes

来源:互联网 发布:知乎b站三国演义 编辑:程序博客网 时间:2024/06/10 22:05

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.

  1. Minimize the total number of operations.
    public void moveZeroes(int[] nums) {        int right = 0; //i是非零元素的index,j是零元素的index          for(int left = 0; left < nums.length; left++) { //left先走,走到不是0元素的时候交换,交换完了right再走            if(nums[left] != 0) {                 int temp = nums[right];                  nums[right] = nums[left];                  nums[left] = temp;                  right++;              }          }      }


0 0