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.
For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [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.
public void moveZeroes(int[] nums) {
int right = 0; //i是非零元素的index,j是零元素的index
for(int left = 0; left < nums.length; left++) { //left先走,走到不是0元素的时候交换,交换完了right再走
if(nums[left] != 0) {
int temp = nums[right];
nums[right] = nums[left];
nums[left] = temp;
right++;
}
}
}
转载请注明原文地址: https://ju.6miu.com/read-200202.html