问题
题目来源于力扣:https://leetcode-cn.com/
给定一个数组 nums, 编写一个函数将所有 0 移动到它的末尾,同时保持非零元素的相对顺序。
例如,定义 nums = [0, 1, 0, 3, 12],调用函数之后, nums 应为 [1, 3, 12, 0, 0]。
解决思路
使用双指针方式。
- 两个指针 p1 和 p2 同时向后移动。
-
p1 遇到 0 则停止,p2 则一直向后移动。
-
如果 p2 遇到的非 0 的数字 p1 和 p2 位置不同时,双方进行替换,并将 p1 后移动一次。
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] nums = {0, 1, 0, 3, 12};
int p1 = 0, p2 = 0;
while (p2 < nums.length) {
if (nums[p2] != 0 && p1 != p2) {
nums[p1] = nums[p2];
nums[p2] = 0;
}
if (nums[p1] != 0) {
p1++;
}
p2++;
}
System.out.println(Arrays.toString(nums));
}
}
输出结果:
[1, 3, 12, 0, 0]
参考
- https://www.csdn.net/tags/MtTacgwsNDY3MTAtYmxvZwO0O0OO0O0O.html (CSDN搜索结果:将数组中的0移动到末尾)