leetcode283 题目详述 题目详解

英文链接:https://leetcode.com/problems/move-zeroes/

中文链接:https://leetcode-cn.com/problems/move-zeroes/

题目详述

给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。

示例:

1
2
输入: [0,1,0,3,12]
输出: [1,3,12,0,0]

说明:

  1. 必须在原数组上操作,不能拷贝额外的数组。
  2. 尽量减少操作次数。

题目详解

  • 遍历过程中把非零元素往前移。
  • 用一个变量记录已经排好的结束位置。
  • 遍历结束后把后面的元素置零即可。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class  {

public void moveZeroes(int[] nums) {
int index = 0;
for (int num : nums) {
if (num != 0) {
nums[index++] = num;
}
}
for (int i = index; i < nums.length; ++i) {
nums[i] = 0;
}
}
}
  • 也可以采用交换的方法把非零元素往前移。
  • 这样最后就不用单独赋零值。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class  {

public void moveZeroes(int[] nums) {
int index = 0;
for (int i = 0; i < nums.length; ++i) {
if (nums[i] != 0) {
swap(nums, index++, i);
}
}
}

private void swap(int[] nums, int i, int j) {
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
}