题解一:
双指针遍历:将非零的值往数组前端依次放置,将放置之后数组后端多余的位置都置为0,参考下图(来源. - 力扣(LeetCode))
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];index++;}}for (int i = index; i < nums.length; i++) {nums[i] = 0;}}
}
题解二:
双指针遍历:类似快速排序,以0作为参照点,将不等于0的值放到左边,将等于0的值放到右边 (二者交换),参考下图(来源. - 力扣(LeetCode))
class Solution {public void moveZeroes(int[] nums) {int index = 0;for (int i = 0; i < nums.length; i++) {if (nums[i] != 0) {int temp = nums[i];nums[i] = nums[index];nums[index] = temp;index++;}}}
}