-
Notifications
You must be signed in to change notification settings - Fork 0
/
RedWhiteAndBlue.java
94 lines (79 loc) · 2.07 KB
/
RedWhiteAndBlue.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
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
83
84
85
86
87
88
89
90
91
92
93
94
/**
* RedWhiteAndBlue
* Level: Medium
* Note: This solution uses Enums and Exceptions. While optional, it always looks good if you use them in an interview.
* You're given a list of Marbles. Each marble can have one of 3 colors (Red, White or Blue).
* Arrange the marbles in order of the colors (Red -> White -> Blue).
* <p>
* Colors are represented as follows:
* 0 - Red
* 1 - White
* 2 - Blue
* <p>
* For example,
* A = [1,0,1,2,1,0,1,2],
* Output = [0,0,1,1,1,1,2,2].
*/
package arraysAndStrings;
import static util.Utils.*;
enum Color {
RED(0),
WHITE(1),
BLUE(2);
public final int colorId;
Color(int colorId) {
this.colorId = colorId;
}
public int getColorId() {
return colorId;
}
}
/**
* @author mandeep
*/
public class RedWhiteAndBlue {
public static void main(String args[]) {
Integer[] arr = {1, 0, 1, 2, 1, 0, 1, 2};
printArray(redWhiteAndBlue(arr));
}
private static Integer[] redWhiteAndBlue(Integer[] arr) {
if (checkIfArrayIsNull(arr))
return arr;
int low = 0, high = arr.length - 1, i = 0;
while (i <= high) {
if (arr[i] == Color.RED.getColorId()) {
swap(arr, i, low);
low++;
i++;
} else if (arr[i] == Color.WHITE.getColorId()) {
i++;
} else if (arr[i] == Color.BLUE.getColorId()) {
swap(arr, i, high);
high--;
} else {
throw new IllegalArgumentException("Unknow Color " + arr[i]);
}
}
return arr;
}
}
class Marble {
private Color color;
private int data;
public Marble(Color color, int data) {
this.color = color;
this.data = data;
}
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
}
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
}