-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMoveZeroes.java
More file actions
47 lines (41 loc) · 1.04 KB
/
MoveZeroes.java
File metadata and controls
47 lines (41 loc) · 1.04 KB
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
45
46
47
package main.code.array;
/**
* @Author: zs
* @Date: 2020/9/27 10:55
*/
public class MoveZeroes {
public static void main(String[] args) {
int[] arr = {1,2,0,4,5,0,6};
for (int i : arr) {
System.out.print(i + " ");
}
System.out.println();
// moveZeroesByTwoPosition(arr);
moveZeroesByMark(arr);
for (int i : arr) {
System.out.print(i + " ");
}
}
public static void moveZeroesByTwoPosition(int[] nums) {
//...省略判空
for (int p = 0, i = 0; i < nums.length; i++) {
if (nums[i] != 0) {
int temp = nums[i];
nums[i] = nums[p];
nums[p++] = temp;
}
}
}
public static void moveZeroesByMark(int[] nums) {
//...省略判空
int index = 0;
for (int num : nums) {
if (num != 0) {
nums[index++] = num;
}
}
while (index < nums.length){
nums[index++] = 0;
}
}
}