-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSortColors.java
More file actions
82 lines (75 loc) · 2.34 KB
/
SortColors.java
File metadata and controls
82 lines (75 loc) · 2.34 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
74
75
76
77
78
79
80
81
82
package sortColor;
import java.util.ArrayList;
import java.util.LinkedList;
class Point {
int val;
Point next;
public Point(int a){
this.val = a;
this.next = null;
}
}
public class SortColors {
public void sortColors(int[] nums){
Point pointZero = null;
Point pointOne = null;
Point head = new Point(-1);
for (int i = 0; i < nums.length; i++){
switch (nums[i]){
case 0:
Point tmp = new Point(0);
tmp.next = head.next;
head.next = tmp;
if (pointZero == null){
pointZero = tmp;
}
break;
case 1:
tmp = new Point(1);
if (pointZero == null){
tmp.next = head.next;
head.next = tmp;
}
else {
tmp.next = pointZero.next;
pointZero.next = tmp;
}
if (pointOne == null){
pointOne = tmp;
}
break;
case 2:
tmp = new Point(2);
if (pointOne == null){
if (pointZero == null){
tmp.next = head.next;
head.next = tmp;
}
else {
tmp.next = pointZero.next;
pointZero.next = tmp;
}
}
else {
tmp.next = pointOne.next;
pointOne.next = tmp;
}
}
}
Point pointer = head.next;
int i = 0;
while (pointer != null){
nums[i] = pointer.val;
pointer = pointer.next;
i++;
}
}
public static void main(String[] args){
SortColors t = new SortColors();
int[] nums = new int[]{1,2,1,1,2,0,1,2};
t.sortColors(nums);
for (int i = 0; i < nums.length; i++){
System.out.println(nums[i]);
}
}
}