leetcode-cn Daily Challenge on November 19th, 2020.
Difficulty : Easy
Related Topics : Array、Two Pointers
Given an array
nums
, write a function to move all0'
s to the end of it while maintaining the relative order of the non-zero elements.Input: [0,1,0,3,12] Output: [1,3,12,0,0]
- You must do this in-place without making a copy of the array.
- Minimize the total number of operations.
- mine
- Java
Runtime: 0 ms, faster than 100.00%, Memory Usage: 39.2 MB, less than 17.70% of Java online submissions
public void moveZeroes(int[] nums) { if (nums == null || nums.length == 0) { return; } int noZeroPos = 0; for (int num : nums) if (num != 0) nums[noZeroPos++] = num; while (noZeroPos < nums.length) nums[noZeroPos++] = 0; }
- Java