原题网址:https://leetcode.com/problems/sort-colors/
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.
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.
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 an one-pass algorithm using only constant space?
方法一:普通排序。
public class Solution {
private void swap(int[] nums, int i, int j) {
int t = nums[i];
nums[i] = nums[j];
nums[j] = t;
}
private void sort(int[] nums, int from, int to) {
if (from>=to) return;
int pivot = from;
for(int i=from; i<to; i++) {
if (nums[i] >= nums[to]) continue;
if (pivot < i) swap(nums, pivot, i);
pivot ++;
}
swap(nums, pivot, to);
sort(nums, from, pivot-1);
sort(nums, pivot+1, to);
}
public void sortColors(int[] nums) {
sort(nums, 0, nums.length-1);
}
}
方法二:桶排序。
public class Solution {
int[] counts = new int[3];
boolean changed = false;
public void sortColors(int[] nums) {
if (changed) Arrays.fill(counts, 0);
changed = true;
for(int i=0; i<nums.length; i++) counts[nums[i]]++;
int pos = 0;
for(int i=0; i<3; i++) {
for(int j=0; j<counts[i]; j++) nums[pos++] = i;
}
}
}

本文介绍了一种不使用库排序函数解决三色排序问题的方法。该问题要求将红色、白色和蓝色对象按顺序排列,分别用0、1和2表示。文章提供了两种解决方案:一种是普通排序方法,另一种是更高效的桶排序方法。
240

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



