Skip to content

Commit 0879ca8

Browse files
author
王俊超
committed
commit
1 parent a4f3992 commit 0879ca8

File tree

3 files changed

+65
-0
lines changed

3 files changed

+65
-0
lines changed

.idea/modules.xml

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
/**
2+
* @author: wangjunchao(王俊超)
3+
* @time: 2018-10-10 17:04
4+
**/
5+
public class Solution {
6+
public void moveZeroes(int[] nums) {
7+
8+
if (nums == null || nums.length < 1) {
9+
return;
10+
}
11+
12+
int idx = 0;
13+
// 找第一个0的位置
14+
while (idx < nums.length && nums[idx] != 0) {
15+
idx++;
16+
}
17+
18+
// 数组的值都非0
19+
if (idx >= nums.length) {
20+
return;
21+
}
22+
23+
int temp = idx + 1;
24+
25+
while (temp < nums.length) {
26+
// 找temp开始第一个非0的位置
27+
while (temp < nums.length && nums[temp] == 0) {
28+
temp++;
29+
}
30+
31+
// 找到非0值,移动到idx位置
32+
if (temp < nums.length) {
33+
nums[idx] = nums[temp];
34+
idx++;
35+
temp++;
36+
}
37+
}
38+
39+
// 从[idx, nums.length-1]的长度都设置为0
40+
for (int i = idx; i < nums.length; i++) {
41+
nums[i] = 0;
42+
}
43+
}
44+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import java.util.Arrays;
2+
3+
/**
4+
* @author: wangjunchao(王俊超)
5+
* @time: 2018-10-10 17:11
6+
**/
7+
public class Test {
8+
public static void main(String[] args) {
9+
moveZeros(new int[]{0, 1, 0, 3, 12});
10+
moveZeros(new int[]{2, 1, 6, 3, 12});
11+
moveZeros(new int[]{2});
12+
moveZeros(new int[]{0});
13+
}
14+
15+
private static void moveZeros(int[] a1) {
16+
Solution solution = new Solution();
17+
solution.moveZeroes(a1);
18+
System.out.println(Arrays.toString(a1));
19+
}
20+
}

0 commit comments

Comments
 (0)