-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSort Colors
More file actions
54 lines (54 loc) · 1.38 KB
/
Sort Colors
File metadata and controls
54 lines (54 loc) · 1.38 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
public class Solution {
public void sortColors(int[] A) {
// Note: The Solution object is instantiated only once and is reused by each test case.
int temp[] = {0,0,0}; //container to temporarily store the three colors
if(A.length == 0) return; //no elements
int left = 0, right = A.length-1;
while(right>left)
{
if(A[right] == 0)
{
if(A[left] == 0)
temp[0]+=1;
else if(A[left] == 1)
temp[1]+=1;
else
temp[2]+=1;
A[left] = 0;
left++;
}
else if(A[right] == 1)
temp[1]+=1;
else
temp[2]+=1;
right--;
if(left == right)
{
if(A[left] == 0)
temp[0]+=1;
else if(A[left] == 1)
temp[1]+=1;
else
temp[2]+=1;
}
}
while(temp[0] != 0)
{
A[left] = 0;
temp[0]-=1;
left++;
}
while(temp[1] != 0)
{
A[left] = 1;
temp[1]-=1;
left++;
}
while(temp[2] != 0)
{
A[left] = 2;
temp[2]-=1;
left++;
}
}
}