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.
Notice
- You must do this in-place without making a copy of the array.
- Minimize the total number of operations.
Example
Given nums = [0, 1, 0, 3, 12]
, after calling your function, nums
should be [1, 3, 12, 0, 0]
.
1 public class Solution { 2 /** 3 * @param nums an integer array 4 * @return nothing, do this in-place 5 */ 6 public void moveZeroes(int[] nums) { 7 // Write your code here 8 if(nums==null|nums.length==0) return; 9 int pos = 0; 10 for(int i=0;i<nums.length;i++){ 11 if(nums[i]!=0){ 12 swap(nums, i, pos++); 13 } 14 } 15 } 16 private void swap(int[] nums, int i, int j){ 17 int temp = nums[i]; 18 nums[i]=nums[j]; 19 nums[j]=temp; 20 } 21 }