forked from chuyi2007/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSortColors.java
More file actions
59 lines (55 loc) · 1.43 KB
/
SortColors.java
File metadata and controls
59 lines (55 loc) · 1.43 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
public class Solution {
public void sortColors(int[] A) {
// Start typing your Java solution below
// DO NOT write main() function
onePass(A);
}
//O(N)
public void onePass(int[] A){
int li = 0, ri = A.length - 1;
for(int mi = 0; mi <= ri; ++mi){
if(A[mi] == 2){
swap(A, mi, ri);
--mi;
--ri;
}
else if(A[mi] == 0){
swap(A, mi, li);
++li;
}
}
}
public void swap(int[] A, int i, int j){
int tmp = A[i];
A[i] = A[j];
A[j] = tmp;
}
//O(N)
public void twoPass(int[] A){
int[] counts = new int[3];
for(int i = 0; i < A.length; i++){
++counts[A[i]];
}
for(int i = 0; i < A.length; i++){
if(i < counts[0])
A[i] = 0;
else if ( i < counts[0] + counts[1])
A[i] = 1;
else
A[i] = 2;
}
}
//O(N^2)
public void brutalSearch(int[] A){
int n = A.length;
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
if(A[i] < A[j]){
int tmp = A[i];
A[i] = A[j];
A[j] = tmp;
}
}
}
}
}