75. 颜色分类

75. 颜色分类

leetcode 75. 颜色分类


题目:75. 颜色分类

给定一个包含红色、白色和蓝色,一共 n 个元素的数组,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。

此题中,我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。

注意:

不能使用代码库中的排序函数来解决这道题。

示例:

输入: [2,0,2,1,1,0]
输出: [0,0,1,1,2,2]

进阶:

  • 一个直观的解决方案是使用计数排序的两趟扫描算法。首先,迭代计算出0、1 和 2 元素的个数,然后按照0、1、2的排序,重写当前数组。
  • 你能想出一个仅使用常数空间的一趟扫描算法吗?

方法一:模拟、统计

思路:统计红色、白色和蓝色各自的数量,然后根据红色、白色和蓝色的顺序和各自对应的数量,重新赋值nums。

运行数据:执行用时:0 ms,内存消耗:38.1 MB

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// LeetCode指定调用方法
public void sortColors(int[] nums) {

// 统计红色、白色和蓝色各自的数量
int[] count = new int[3];
for (int i : nums) {
count[i]++;
}

// 根据红色、白色和蓝色的顺序和各自对应的数量,重新赋值nums
int t = 0;
for (int i = 0; i < count.length; i++) {
while (count[i]-- > 0) {
nums[t++] = i;
}
}
}

方法二:荷兰国旗问题

思路:将数组视为红色、白色和蓝色(左、中、右)三个区间,使用三个变量标识区间元素位置,一开始认为整个数组都为白色区间,遍历白色区间,找到不满足白色区间的元素 ,将其与该元素对应区间的标识位置的的元素做交换,直至遍历到蓝色区间,即白色区间遍历结束为止。

运行数据:执行用时:0 ms,内存消耗:38.4 MB

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// LeetCode指定调用方法
public void sortColors(int[] nums) {

// 红色、白色和蓝色三个区间对应的标识指针
int red = -1, white = 0, blue = nums.length;

// 遍历白色区间
while (white < blue) {
if (nums[white] == 0) { // 找到不满足白色区间的元素,此时该元素应为红色区间
swap(nums, ++red, white++);
} else if (nums[white] == 2) { // 找到不满足白色区间的元素,此时该元素应为蓝色区间
swap(nums, white, --blue);
} else {
white++;
}
}
}

// 交换
private void swap(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}

学习所得,资料、图片部分来源于网络,如有侵权,请联系本人删除。

才疏学浅,若有错误或不当之处,可批评指正,还请见谅!


 
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×