1、题目名称
Sort Colors(对颜色排序)
2、题目地址
https://leetcode.com/problems/sort-colors/
3、题目内容
英文:
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.
中文:
给定一个内含n个由红色、白色和蓝色对象组成的数组,对这些对象进行排序。在本题中,红色用0表示,白色用1表示,蓝色用2表示。
4、解题方法1
虽然题目中的Hint建议你不要使用各个语言提供的Sort类函数解决本问题,但使用Arrays.sort还是可以AC本题的。
Java代码如下:
import java.util.Arrays;
/**
* 为颜色排序
* @文件名称 Solution.java
* @文件作者 Tsybius2014
* @创建时间 2016年4月16日 上午12:17:49
*/
public class Solution {
public void sortColors(int[] nums) {
Arrays.sort(nums);
}
}
5、解题方法2
后来看了下讨论区,才发现这道题其实考的是“荷兰国旗问题”。
关于“荷兰国旗问题”的描述,可以参考维基百科相关页面:
https://en.wikipedia.org/wiki/Dutch_national_flag_problem
关于“荷兰国旗问题”的解决方法,这篇文章有较为详细的论述:
http://www.cnblogs.com/gnuhpc/archive/2012/12/21/2828166.html
大体思路是使用三个标记begin、curr、end,其中在遍历过程中,begin以前的对象全部是红色的,end以后的对象全部是蓝色的,迭代到最后,begin与end之间的对象一定是白色的。
解题Java代码如下:
/**
* 为颜色排序
* @文件名称 Solution.java
* @文件作者 Tsybius2014
* @创建时间 2016年4月16日 上午12:17:49
*/
public class Solution {
public void sortColors(int[] nums) {
int begin = 0;
int curr = 0;
int end = nums.length - 1;
int temp = 0;
while (curr <= end) {
if (nums[curr] == 0) {
if (begin != curr) {
temp = nums[begin];
nums[begin] = nums[curr];
nums[curr] = temp;
}
begin++;
curr++;
} else if (nums[curr] == 1) {
curr++;
} else if (nums[curr] == 2) {
if (end != curr) {
temp = nums[end];
nums[end] = nums[curr];
nums[curr] = temp;
}
end--;
}
}
}
}
END