-
Notifications
You must be signed in to change notification settings - Fork 0
/
283-移动零.java
44 lines (33 loc) · 933 Bytes
/
283-移动零.java
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
class Solution {
//方法一:
public void moveZeroes(int[] nums) {
if (nums == null || nums.length == 0)
return;
int index = 0;
//一次遍历,把非零的都往前挪
for (int i = 0; i < nums.length; i++) {
if (nums[i] != 0)
nums[index++] = nums[i];
}
//后面的都是0,
while (index < nums.length) {
nums[index++] = 0;
}
}
//方法二:
public static void moveZeroes(int[] nums) {
int tempZero = 0;
for (int i = 0; i < nums.length-tempZero; ) {
if (nums[i]==0){
for (int j = i,k=j+1; j < k&&k<nums.length-tempZero; j++,k++) {
nums[j]=nums[k];
nums[k]=0;
}
i=0;
tempZero++;
continue;
}
i++;
}
}
}