leetcode 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].

这道题的意思就是将一个数组里面的全部0移到数组的最后,同时要保持数组的非零元素顺序不变数组

同时这道题也有额外的要求:不能声明一个新的拷贝的数组以及尽可能减小操做的次数code

思路

  • 由于题目不容许咱们新声明一个数组,并且非零元素都排在新数组的最前面。
  • 所以咱们有这样一个想法:用一个值保存当前遍历到的非零元素数量,并将第i个元素赋值给数组下标为i-1的元素。这样后面剩下的位置,都赋值为0便可知足题目的要求。

解法

public void moveZeroes(int[] nums) {
        if(nums != null && nums.length == 0) return;
        int insertPost = 0;
        for(int num : nums){
            if(num != 0){
                nums[insertPost++] = num;
            }
        }
        while(insertPost < nums.length){
            nums[insertPost++] = 0;
        }
}