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]
class Solution {
// 把0移动到最后 <==> 把非0的移动到前面
public void moveZeroes(int[] nums) {
// 记录移动了一个非零元素到前面
// 当移动了move个非零元素到前面时,说明前move个都是移动过的,此时再往前移动时应放在 move位置,才不会破坏顺序
int move = 0;
// 记录遍历到第几个
int index = 0;
while (index < nums.length) {
// 如果nums[index]!=0,说明它需要移动到move位置上,并且move+1
// 除了第一次循环以外,move位置的元素一定是0,因为循环到index时,遇到了move个非0,全移动到最前面了,所以move位置肯定是0
if (nums[index] != 0) {
int temp = nums[move];
nums[move] = nums[index];
nums[index] = temp;
move++;
}
index++;
}
}
}
原文:https://www.cnblogs.com/zebinlin/p/9969872.html