283. Move Zeroes
Given an arraynums
, write a function to move all0
's to the end of it while maintaining the relative order of the non-zero elements.
For example, givennums = [0, 1, 0, 3, 12]
, after calling your function,nums
should be[1, 3, 12, 0, 0]
.
Note:
- You must do thisin-placewithout making a copy of the array.
- Minimize the total number of operations.
对数组进行排序,要求大于0的数字在数组的前面,后面为0,且数字的相对顺序不发生改变。
方法1
非0数字前移,后面的数字全补为0
class Solution { public void moveZeroes(int[] nums) { int index = 0; for(int i = 0; i < nums.length; i++) if(nums[i] != 0) nums[index ++] = nums[i]; for(int i = index; i < nums.length; i++) nums[i] = 0; } }
方法2
public void moveZeroes(int[] nums) { int j = 0; for(int i = 0; i < nums.length; i++) { if(nums[i] != 0) { int temp = nums[j]; nums[j] = nums[i]; nums[i] = temp; j++; }
}