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:
- You must do this in-place without making a copy of the array.
- Minimize the total number of operations.
//Time: O(n), Space: O(1) //注意:这道题关键是想明白如果i, j都指向非0,那么其实是自己和自己交换。 //否则双指针,j用来找非零,i指向当前排好的位置 public void moveZeroes(int[] nums) { if (nums == null || nums.length == 0) { return; } int j = 0; for (int i = 0; i < nums.length; i++) { if (nums[i] != 0) { swap(i, j, nums); j++; } } } private void swap(int i, int j, int[] nums) { int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; }