Skip to content

Commit 5fc3181

Browse files
committed
solve 75.sort-colors
1 parent a50fae6 commit 5fc3181

File tree

1 file changed

+13
-17
lines changed

1 file changed

+13
-17
lines changed

vscode/75.sort-colors.java

Lines changed: 13 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -42,27 +42,23 @@
4242
*/
4343
class Solution {
4444
public void sortColors(int[] nums) {
45-
Map<Integer, Integer> map = new HashMap<>();
45+
int zero = 0;
46+
int second = nums.length - 1;
4647

47-
for (int i = 0; i < nums.length; i++) {
48-
if (map.containsKey(nums[i])) {
49-
map.put(nums[i], map.get(nums[i]) + 1);
50-
} else {
51-
map.put(nums[i], 1);
48+
for (int i = zero; i <= second; i++) {
49+
while (nums[i] == 2 && i < second) {
50+
swap(nums, i, second--);
5251
}
53-
}
54-
55-
int k = 0;
56-
for (int key = 0; key <= 2; key++) {
57-
int count = 0;
58-
if (map.containsKey(key)) {
59-
count = map.get(key);
60-
}
61-
while (count > 0) {
62-
nums[k++] = key;
63-
count--;
52+
while (nums[i] == 0 && i > zero) {
53+
swap(nums, i, zero++);
6454
}
6555
}
6656
}
57+
58+
public void swap(int[] nums, int i, int j) {
59+
int temp = nums[i];
60+
nums[i] = nums[j];
61+
nums[j] = temp;
62+
}
6763
}
6864

0 commit comments

Comments
 (0)