283. Move Zeroes

2019/11/05 Leetcode

283. Move Zeroes

Tags: ‘Array’, ‘Two Pointers’

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.

Example:

Input: [0,1,0,3,12]
Output: [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.

Solution

跟Move Element 一样,只不过最后要把尾部全设为0

public void moveZeroes(int[] nums) {
    if (nums == null || nums.length == 0) return;
    
    int i = 0; // point to after-end of target array
    for (int j = 0; j < nums.length; j++) {
        if (nums[j] != 0) {
            nums[i] = nums[j];
            i++;
        }
    }
    for (int j = i; j < nums.length; j++) {
        nums[j] = 0;
    }
}

Search

    Table of Contents