1、LeetCode 链接
- 官方链接:https://leetcode.cn/problems/move-zeroes/description/?envType=study-plan-v2&envId=top-100-liked
- 标签:数组
plain
给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
请注意 ,必须在不复制数组的情况下原地对数组进行操作。
示例 1:
输入: nums = [0,1,0,3,12]
输出: [1,3,12,0,0]
示例 2:
输入: nums = [0]
输出: [0]
提示:
1 <= nums.length <= 104
-231 <= nums[i] <= 231 - 1
进阶:你能尽量减少完成的操作次数吗?
2、个人写法
- 思路:从头遍历数组,如果是0就将该元素和后面的第一个非零数字交换,这样保持非零元素的相对顺序
- 时间复杂度:O(N2)
- 空间复杂度:O(1)
plain
class Solution {
public void moveZeroes(int[] nums) {
int length = nums.length;
int last = length - 1;
for (int i = 0; i < length; i++) {
if (nums[i] == 0) {
boolean allZero = true;
for (int j = i + 1; j < length; j++) {
if (nums[j] != 0) {
allZero = false;
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
break;
}
}
if (allZero) {
break;
}
}
}
}
}
3、更优写法
- 思路:遍历元素,第一个非零元素放在index=0位置,第二个非零元素放在index=1,依此类推
- 时间复杂度:O(N)
- 空间复杂度:O(1)
plain
class Solution {
public void moveZeroes(int[] nums) {
int index = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] != 0) {
if (index != i) {
// 交换位置
int temp = nums[i];
nums[i] = nums[index];
nums[index] = temp;
}
// 在此轮交换位置后, 下一次就应该将非零元素交换到下一个位置了
index++;
}
}
}
}