1. Description
Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue.
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.
Example:
Input: [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]
Follow up:
A rather straight forward solution is a two-pass algorithm using counting sort.
First, iterate the array counting number of 0’s, 1’s, and 2’s, then overwrite array with total number of 0’s, then 1’s and followed by 2’s.
Could you come up with a one-pass algorithm using only constant space?
2. Method
Quick Sort
- pick an element as pivot (always the first element)
- put all elements that lass than or equal before the pivot
- put all elements that bigger than pivot behind it
- divide and conquer
实现代码
class Solution {
public void sortColors(int[] nums) {
quickSort(nums, 0, nums.length-1);
return;
}
//Quick Sort
public void quickSort(int[] nums, int l, int r){
if(r <= l){
return;
}
int x = nums[l];
int i = l;
int j = r;
//make all elements behind i are bigger or equal x
//make all elements before i are less x
while(i < j){
//from tail to head
while(i < j && nums[j] >= x){
j--;
}
if(i < j){
nums[i] = nums[j];
i++;
}
//from head to tail
while(i < j && nums[i] < x){
i++;
}
if(i < j){
nums[j] = nums[i];
j--;
}
}
//when i == j
nums[i] = x;
//next, we need to divide and conquer
quickSort(nums, l, i-1);
quickSort(nums, i+1, r);
}
}

本文深入探讨了三色排序问题,即如何将红、白、蓝三种颜色的对象按顺序排列。通过使用计数排序和快速排序两种方法,文章详细解释了如何在常数空间内一过完成排序过程。附带的代码示例展示了快速排序的具体实现。
1138

被折叠的 条评论
为什么被折叠?



