forked from rpj911/LeetCode_algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSortKColors.java
More file actions
117 lines (95 loc) · 3.18 KB
/
SortKColors.java
File metadata and controls
117 lines (95 loc) · 3.18 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
package Algorithms.lintcode.array;
class SortKColors {
public static void main(String[] strs) {
int A[] = {2,2,3,1,1,1,2,3,2,2};
sortKColors(A, 3);
for (int i = 0; i < A.length; i++) {
System.out.print(" " + A[i]);
}
}
/**
* @param colors: A list of integer
* @param k: An integer
* @return: nothing
*/
/*
Solution 1: Using the quick sort.
*/
public static void sortKColors1(int[] colors, int k) {
// write your code here
if (colors == null) {
return;
}
quickSort(colors, 0, colors.length - 1);
}
public static void quickSort(int[] colors, int left, int right) {
if (left >= right) {
return;
}
int pivot = colors[right];
int pos = partition(colors, left, right, pivot);
quickSort(colors, left, pos - 1);
quickSort(colors, pos + 1, right);
}
public static int partition(int[] colors, int left, int right, int pivot) {
int leftPoint = left - 1;
int rightPoint = right;
while (true) {
while (colors[++leftPoint] < pivot);
while (leftPoint < rightPoint && colors[--rightPoint] > pivot);
if (leftPoint >= rightPoint) {
break;
}
swap(colors, leftPoint, rightPoint);
}
swap(colors, leftPoint, right);
return leftPoint;
}
public static void swap(int[] colors, int left, int right) {
int tmp = colors[left];
colors[left] = colors[right];
colors[right] = tmp;
}
// Solution 2: inplace, O(n)
public static void sortKColors(int[] colors, int k) {
// write your code here
if (colors == null) {
return;
}
int len = colors.length;
for (int i = 0; i < len; i++) {
// Means need to deal with A[i]
while (colors[i] > 0) {
int num = colors[i];
if (colors[num - 1] > 0) {
// 1. There is a number in the bucket,
// Store the number in the bucket in position i;
colors[i] = colors[num - 1];
colors[num - 1] = -1;
} else if (colors[num - 1] < 0) {
// 2. Bucket is using.
colors[num - 1]--;
// delete the A[i];
colors[i] = 0;
} else if (colors[num - 1] == 0) {
// 3. The bucket is empty.
colors[num - 1] = -1;
// delete the A[i];
colors[i] = 0;
}
}
}
int index = len - 1;
for (int i = k - 1; i >= 0; i--) {
int cnt = -colors[i];
// Empty number.
if (cnt == 0) {
continue;
}
while (cnt > 0) {
colors[index--] = i + 1;
cnt--;
}
}
}
}