欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

283. Move zeros

程序员文章站 2024-02-17 10:32:16
...

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, `nuts` 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.

思路

  1. 将所有的非0数向前尽可能的压缩,最后把没压缩的那部分全置0就行了。比如nums = [0, 1, 0, 3, 12],先压缩成[1, 3, 12], 剩余的2个数为全置为0。
  2. 用一个指针记录压缩到的位置。
class Solution {
    public void moveZeroes(int[] nums) {
        if (nums == null || nums.length == 0) return;
        
        int endNewArray = 0;
        
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] != 0) {
                nums[endNewArray] = nums[i];
                endNewArray++;
                continue;
            }
        }
        
        for (; endNewArray < nums.length; endNewArray++) {
            nums[endNewArray] = 0;
        }
    }
}