Given an integer array nums
, move all 0
's to the end of it while maintaining the relative order of the non-zero elements.
Note that you must do this in-place without making a copy of the array.
Example 1:
Input: nums = [0,1,0,3,12]
Output: [1,3,12,0,0]
Could you minimize the total number of operations done?
class Solution { public void moveZeroes(int[] nums) { for (int i = nums.length - 1; i >= 0; i--) { if (nums[i] == 0) { for (int j = i; j < nums.length - 1; j++) { if (nums[j + 1] != 0) swap(nums, j, j + 1); else break; } } } } private void swap(int[] nums, int i, int j) { int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; } }
class Solution { public void moveZeroes(int[] nums) { if (nums == null || nums.length == 0) return; int start = 0; int index = 0; while (index < nums.length) { if (nums[index] != 0) { nums[start++] = nums[index]; } index++; } while (start < nums.length) nums[start++] = 0; } }