-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetCode283.java
More file actions
73 lines (67 loc) · 1.77 KB
/
LeetCode283.java
File metadata and controls
73 lines (67 loc) · 1.77 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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import java.util.Arrays;
import util.PrintUtil;
public class LeetCode283 {
public static void main(String[] args) {
int[] nums;
// 输入: nums = [0,1,0,3,12]
// 输出: [1,3,12,0,0]
nums = new int[] { 0, 1, 0, 3, 12 };
System.out.println(Arrays.toString(nums));
new Solution283_2().moveZeroes(nums);
System.out.println(Arrays.toString(nums));
PrintUtil.printDivider();
// 输入: nums = [0]
// 输出: [0]
nums = new int[] { 0 };
System.out.println(Arrays.toString(nums));
new Solution283_2().moveZeroes(nums);
System.out.println(Arrays.toString(nums));
PrintUtil.printDivider();
}
}
/**
* 过于繁琐
*/
class Solution283_1 {
public void moveZeroes(int[] nums) {
if (nums.length == 1) {
return;
}
int index = 0;
int firstZero = -1;
while (index < nums.length) {
if (nums[index] == 0) {
firstZero = index;
break;
}
index++;
}
while (index < nums.length) {
if (nums[index] != 0) {
swap(nums, index, firstZero);
firstZero++;
}
index++;
}
}
public void swap(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
class Solution283_2 {
public void moveZeroes(int[] nums) {
if (nums == null || nums.length == 0) {
return;
}
int j = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] != 0) {
int temp = nums[i];
nums[i] = nums[j];
nums[j++] = temp;
}
}
}
}