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

你可能感兴趣的:(283. Move Zeroes)