Repository navigation
Expand file tree
/
Copy path75_Sort_Colors.java
More file actions
95 lines (87 loc) · 2.44 KB
/
Copy path75_Sort_Colors.java
File metadata and controls
95 lines (87 loc) · 2.44 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
/*
* 75. Sort Colors
* Target: Given an array with n objects colored red, white or blue, sort them in-place so that
* objects of the same color are adjacent, with the colors in the order red, white and blue.
* Difficulty:Medium
* Classification:Array, Two pointers, Sort
*/
/*
* Solution 1
* 2019-06-27 Runtime: 2 ms
* Algorithm: => First, iterate the array counting number of 0's, 1's, and 2's,
* then overwrite array with total number of 0's, then 1's and followed by 2's.
* Time complexity: O(n) Space complexity: O(1)
*/
class Solution {
public void sortColors(int[] nums) {
int num0 = 0;
int num1 = 0;
for (int num : nums) {
if (num == 0) {
num0++;
}
if (num == 1) {
num1++;
}
}
System.out.println(num1);
for (int i = 0; i < num0; i++) {
nums[i] = 0;
}
for (int i = num0; i < num0 + num1; i++) {
nums[i] = 1;
}
for (int i = num0 + num1; i < nums.length; i++) {
nums[i] = 2;
}
}
}
/*
* Solution 2
* 2019-06-27 Runtime: 0 ms
* Algorithm: => Two pointers.
* Time complexity: O(n) Space complexity: O(1)
*/
class Solution {
public void sortColors(int[] nums) {
int pos_z = 0;
int pos_t = nums.length - 1;
for (int i = 0; i <= pos_t; i++) {
if (nums[i] == 0) {
int tmp = nums[i];
nums[i] = nums[pos_z];
nums[pos_z] = tmp;
pos_z++;
} else if (nums[i] == 2) {
int tmp = nums[i];
nums[i] = nums[pos_t];
nums[pos_t] = tmp;
pos_t--;
i--; // Note that we should check the number from pos_t before i++.
}
}
}
}
/*
* Solution 3
* 2019-06-27 Runtime: 0 ms
* Algorithm: => Three pointers
* Time complexity: O(n) Space complexity: O(1)
*/
class Solution {
public void sortColors(int[] nums) {
int n0 = -1, n1 = -1, n2 = -1;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == 0) {
nums[++n2] = 2;
nums[++n1] = 1;
nums[++n0] = 0;
} else if (nums[i] == 1) {
nums[++n2] = 2;
nums[++n1] = 1;
} else {
nums[++n2] = 2;
}
}
}
}