LeetCode 283. Move Zeroes
LeetCode 283. Move Zeroes (移动零)
题目
链接
https://leetcode-cn.com/problems/move-zeroes
问题描述
给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
示例
输入: [0,1,0,3,12]
输出: [1,3,12,0,0]
提示
必须在原数组上操作,不能拷贝额外的数组。
尽量减少操作次数。
思路
数组操作题,快慢指针,如果不为0就写入,如果为0就忽略。
最后再把后面的位置全部改为0.
复杂度分析
时间复杂度 O(n)
空间复杂度 O(1)
代码
Java
public static void moveZeroes(int[] nums) {
int fast = 0, slow = 0;
while (fast < nums.length) {
if (nums[fast] != 0) {
nums[slow] = nums[fast];
slow++;
}
fast++;
}
while (slow < nums.length) {
nums[slow++] = 0;
}
}

浙公网安备 33010602011771号