-
Notifications
You must be signed in to change notification settings - Fork 11
/
SortColors.java
58 lines (49 loc) · 1.36 KB
/
SortColors.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
public class SortColors {
/*双指针解法*/
public static void sortColors(int[] nums){
int n = nums.length;
int p0 = 0;
int p1 = 0;
for (int i = 0; i < n; i++) {
if (nums[i] == 1){
swap(nums,i,p1);
++p1;
}else if (nums[i] == 0){
swap(nums,i,p0);
if (p0 < p1) {
swap(nums,i,p1);
}
++p0;
++p1;
}
}
}
/*单指针解法*/
public static void sortColorsSinglePtr(int[] nums) {
int ptr = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == 0){
swap(nums,i,ptr);
ptr++;
}
}
for (int j = ptr; j < nums.length; j++) {
if (nums[j] == 1){
swap(nums,j,ptr);
ptr++;
}
}
}
public static void swap(int[] nums,int left ,int right){
int temp = nums[left];
nums[left] = nums[right];
nums[right] = temp;
}
public static void main(String[] args) {
int[] nums = new int[]{2,0,2,1,1,0};
sortColors(nums);
for (int i = 0; i < nums.length; i++) {
System.out.println(nums[i]);
}
}
}