Fork me on GitHub

LeetCode-283:移动零

1
本题为LeetCode第283道题,为简单题


给定一个数组 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
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
* @author RickYinPeng
* @ClassName Move_Zeroes
* @Description LeetCode中第283道题
* @date 2018/10/5/22:18
*
* 题目名称:移动零
*/
public class Move_Zeroes {

public static void main(String[] args) {
int[] nums = {0,1,0,3,12};
moveZeroes(nums);
System.out.println(Arrays.toString(nums));

}
public static void moveZeroes(int[] nums) {
for(int i = 0;i<nums.length;i++){
if(nums[i]==0 && i!=nums.length-1){
for(int j = i+1;j<nums.length;j++){
if(nums[j]!=0){
nums[i] = nums[j];
nums[j] = 0;
break;
}
}
}
}
}
}

这道题没啥难度,我就不多说了,再贴上大佬的代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public void moveZeroes(int[] nums) {
int counter = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == 0) {
counter++;
} else {
nums[i-counter] = nums[i];
if (counter > 0)
nums[i] = 0;
}
}
}
}

秀吧!!!