文章目录
- 题目
- 题解
题目
原题链接:移动零
题解
思路:快慢指针(双指针)法
- 慢指针(l):用于标记当前非零元素应该存放的位置。
- 快指针(h):用于遍历整个数组。
public class Test {public static void moveZeroes(int[] nums) {int l = 0, h = 0;for (; h < nums.length; h++) {if (nums[h] != 0) {nums[l++] = nums[h];}}for (; l < nums.length; l++) {nums[l] = 0;}}public static void main(String[] args) {int[] nums = {0, 1, 0, 3, 12};moveZeroes(nums);System.out.println(Arrays.toString(nums));}
}
❤觉得有用的可以留个关注❤