File tree Expand file tree Collapse file tree 1 file changed +68
-0
lines changed Expand file tree Collapse file tree 1 file changed +68
-0
lines changed Original file line number Diff line number Diff line change
1
+ #### 75. 颜色分类
2
+
3
+ 难度:中等
4
+
5
+ ---
6
+
7
+ 给定一个包含红色、白色和蓝色、共 ` n ` 个元素的数组 ` nums ` , ** [ 原地] ( https://baike.baidu.com/item/%E5%8E%9F%E5%9C%B0%E7%AE%97%E6%B3%95 ) ** 对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。
8
+
9
+ 我们使用整数 ` 0 ` 、 ` 1 ` 和 ` 2 ` 分别表示红色、白色和蓝色。
10
+
11
+ 必须在不使用库内置的 sort 函数的情况下解决这个问题。
12
+
13
+ ** 示例 1:**
14
+
15
+ ```
16
+ 输入:nums = [2,0,2,1,1,0]
17
+ 输出:[0,0,1,1,2,2]
18
+ ```
19
+
20
+ ** 示例 2:**
21
+
22
+ ```
23
+ 输入:nums = [2,0,1]
24
+ 输出:[0,1,2]
25
+ ```
26
+
27
+ ** 提示:**
28
+
29
+ * ` n == nums.length `
30
+ * ` 1 <= n <= 300 `
31
+ * ` nums[i] ` 为 ` 0 ` 、` 1 ` 或 ` 2 `
32
+
33
+ ** 进阶:**
34
+
35
+ * 你能想出一个仅使用常数空间的一趟扫描算法吗?
36
+
37
+ ---
38
+
39
+ 双指针:
40
+
41
+ ** 尾指针** 指向最后,** 头指针** 指向最前。另外需要一个** 遍历指针** 从头向尾遍历,然后分类讨论(重要):
42
+
43
+ 1 . 如果当前元素为 ` 0 ` ,与头指针元素交换并将遍历指针和头指针都向右移动一个单位。
44
+ 2 . 如果当前元素为 ` 1 ` ,只移动遍历指针
45
+ 3 . 如果当前元素为 ` 2 ` ,与尾指针元素交换并左移尾指针,此时不移动遍历指针!!!
46
+
47
+ ``` Java
48
+ class Solution {
49
+ public void sortColors (int [] nums ) {
50
+ int left = 0 , right = nums. length - 1 , index = 0 ;
51
+ while (index <= right){
52
+ if (nums[index] == 2 ){
53
+ swap(nums, index, right-- );
54
+ continue ;
55
+ } else if (nums[index] == 0 ){
56
+ swap(nums, left++ , index);
57
+ }
58
+ index++ ;
59
+ }
60
+ }
61
+
62
+ private void swap (int [] nums , int left , int right ){
63
+ int temp = nums[left];
64
+ nums[left] = nums[right];
65
+ nums[right] = temp;
66
+ }
67
+ }
68
+ ```
You can’t perform that action at this time.
0 commit comments