283.移动零
思路:
本题使用快慢指针法。
双指针法(快慢指针法)在数组和链表的操作中是非常常见的,
很多考察数组、链表、字符串等操作的面试题,都使用双指针法。
使用快慢指针把数组前面的元素排好,后面补0即可
代码实现
class Solution {
public void moveZeroes(int[] nums) {
int slowIndex = 0;
for (int fastIndex = 0; fastIndex < nums.length; fastIndex++) {
if (nums[fastIndex] != 0) {
nums[slowIndex++] = nums[fastIndex];
}
}
for (int i = slowIndex; i < nums.length; i++) {
nums[i] = 0;
}
}
}