描述
Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue.
【Leetcode 75. Sort Colors】Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
Note:
You are not suppose to use the library’s sort function for this problem.
For example: [1,2,1,1,0,0,2,1,0]
思路
- 思路1:快速排序的变体,见《算法-第四版》P189
- 思路2:桶排序
- 更正一下思路一:这道题其实可能可以不用递归调用的,因为只有三个数,一次运行后,有可能就会对的,但是必须保证切分点是中间值,如原始输入为[1,0,2]可以Accept,[0,1,2]就不能过。所以还是需要递归。
快速排序
class Solution {public void exch(int[] nums, int i, int j){
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}public void sortQuickThreeWay(int[] nums, int lo, int hi){
if (hi <= lo)
return;
int less = lo;
int i = lo + 1;
int great = hi;
int v = nums[lo];
while(i <= great){
if (nums[i] < v) exch(nums, less++, i++);
else if (nums[i] > v) exch(nums, i, great--);
else i++;
}
sortQuickThreeWay(nums, lo, less-1);
sortQuickThreeWay(nums, great+1, hi);
}public void sortColors(int[] nums) {
sortQuickThreeWay(nums, 0, nums.length-1);
}
}
桶排序
class Solution {public void sortColors(int[] nums) {
if (nums.length <= 1){
return;
}
int[] states = new int[3];
for (int i = 0;
i < nums.length;
i++){
states[nums[i]]++;
}
for (int j = 1;
j < 3;
j++){
states[j] += states[j-1];
}
Arrays.fill(nums, 0, states[0], 0);
Arrays.fill(nums, states[0], states[1], 1);
Arrays.fill(nums, states[1], states[2], 2);
}
}
推荐阅读
- 人工智能|干货!人体姿态估计与运动预测
- 分析COMP122 The Caesar Cipher
- 技术|为参加2021年蓝桥杯Java软件开发大学B组细心整理常见基础知识、搜索和常用算法解析例题(持续更新...)
- C语言学习(bit)|16.C语言进阶——深度剖析数据在内存中的存储
- Python机器学习基础与进阶|Python机器学习--集成学习算法--XGBoost算法
- 数据结构与算法|【算法】力扣第 266场周赛
- 数据结构和算法|LeetCode 的正确使用方式
- leetcode|今天开始记录自己的力扣之路
- 人工智能|【机器学习】深度盘点(详细介绍 Python 中的 7 种交叉验证方法!)
- 网络|简单聊聊压缩网络