Skip to content

Commit 6ac7daa

Browse files
committed
📝 update leetcode 75
1 parent aed1acc commit 6ac7daa

File tree

5 files changed

+99
-0
lines changed

5 files changed

+99
-0
lines changed

.DS_Store

0 Bytes
Binary file not shown.

Java/.DS_Store

0 Bytes
Binary file not shown.

Java/alg/.DS_Store

0 Bytes
Binary file not shown.

Java/alg/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,7 @@
123123
- [63.不同路径2](lc/63.不同路径2.md)
124124
- [64.最小路径和](lc/64.最小路径和.md)
125125
- [74. 搜索二维矩阵](lc/74.搜索二维矩阵.md)
126+
- [75.颜色分类](lc/75.颜色分类.md)
126127

127128
## 笔试
128129

Java/alg/lc/75.颜色分类.md

Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
# 75. 颜色分类
2+
3+
[url](https://leetcode-cn.com/problems/sort-colors/)
4+
5+
## 题目
6+
7+
给定一个包含红色、白色和蓝色,一共 n 个元素的数组,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。此题中,我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。
8+
9+
10+
```
11+
输入:nums = [2,0,2,1,1,0]
12+
输出:[0,0,1,1,2,2]
13+
输入:nums = [2,0,1]
14+
输出:[0,1,2]
15+
输入:nums = [0]
16+
输出:[0]
17+
```
18+
19+
20+
21+
22+
## 方法
23+
24+
25+
26+
27+
## code
28+
29+
### js
30+
31+
```js
32+
let sortColors = nums => {
33+
let swap = (a, i, j) => {
34+
let t = a[i];
35+
a[i] = a[j];
36+
a[j] = t;
37+
}
38+
let zero = -1, one = 0, two = nums.length;
39+
while (one < two) {
40+
if (nums[one] === 0)
41+
swap(nums, ++zero, one++);
42+
else if (nums[one] === 2)
43+
swap(nums, --two, one);
44+
else
45+
++one;
46+
}
47+
}
48+
```
49+
50+
### go
51+
52+
```go
53+
func sortColors(nums []int) {
54+
swap := func(a []int, i, j int) {
55+
a[i], a[j] = a[j], a[i]
56+
}
57+
zero, one, two := -1, 0, len(nums)
58+
for one < two {
59+
if nums[one] == 0 {
60+
zero++
61+
swap(nums, zero, one)
62+
one++
63+
} else if nums[one] == 2 {
64+
two--
65+
swap(nums, two, one)
66+
} else {
67+
one++
68+
}
69+
}
70+
}
71+
```
72+
73+
74+
75+
### java
76+
77+
```java
78+
class Solution {
79+
public void sortColors(int[] nums) {
80+
int zero = -1, one = 0, two = nums.length;
81+
while (one < two) {
82+
if (nums[one] == 0) {
83+
swap(nums, ++zero, one++);
84+
} else if (nums[one] == 2){
85+
swap(nums, --two, one);
86+
} else {
87+
++one;
88+
}
89+
}
90+
}
91+
private void swap(int[] a, int i, int j) {
92+
int t = a[i];
93+
a[i] = a[j];
94+
a[j] = t;
95+
}
96+
}
97+
```
98+

0 commit comments

Comments
 (0)