Skip to content

Commit a495847

Browse files
author
王鹏
committed
feat(EASY): add _283_moveZeroes
1 parent 7b88fa9 commit a495847

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
package pp.arithmetic.leetcode;
2+
3+
import pp.arithmetic.Util;
4+
5+
/**
6+
* Created by wangpeng on 2019-08-07.
7+
* 283. 移动零
8+
* <p>
9+
* 给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
10+
* <p>
11+
* 示例:
12+
* <p>
13+
* 输入: [0,1,0,3,12]
14+
* 输出: [1,3,12,0,0]
15+
* 说明:
16+
* <p>
17+
* 必须在原数组上操作,不能拷贝额外的数组。
18+
* 尽量减少操作次数。
19+
* <p>
20+
* 来源:力扣(LeetCode)
21+
* 链接:https://leetcode-cn.com/problems/move-zeroes
22+
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
23+
*/
24+
public class _283_moveZeroes {
25+
public static void main(String[] args) {
26+
_283_moveZeroes moveZeroes = new _283_moveZeroes();
27+
int[] nums = {0, 1, 0, 3, 12};
28+
moveZeroes.moveZeroes(nums);
29+
Util.printArray(nums);
30+
}
31+
32+
/**
33+
* 解题思路:
34+
* 1.遍历数组,找到第一个0并标记zeroIndex
35+
* 2.找到下一个非0,将其与0交互,zeroIndex++
36+
* 3.找到下一个0,不做任何处理
37+
*
38+
* @param nums
39+
*/
40+
public void moveZeroes(int[] nums) {
41+
int zeroIndex = -1;
42+
//1
43+
for (int i = 0; i < nums.length; i++) {
44+
int num = nums[i];
45+
if (num == 0) {
46+
//1
47+
if (zeroIndex == -1) {
48+
zeroIndex = i;
49+
}
50+
//3
51+
} else {
52+
//2
53+
if (zeroIndex != -1) {
54+
nums[zeroIndex] = num;
55+
nums[i] = 0;
56+
zeroIndex++;
57+
}
58+
}
59+
}
60+
}
61+
}

0 commit comments

Comments
 (0)