# 题目描述

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.

# 题目解答

#### 解题思路

• 先统计red , white, blue 三组颜色的个数，然后分别按照颜色的个数建立数组
• 双指针法

#### 代码实现

• 计数排序
public class Solution {
public void sortColors(int[] nums) {
if(nums == null || nums.length == 0)
return ;
int redCount = 0, whiteCount = 0, blueCount = 0;
for(int i = 0; i < nums.length; i++){
switch(nums[i]){
//红色
case 0:
redCount++;
break;
case 1:
whiteCount++;
break;
case 2:
blueCount++;
break;
default:
}
}
for(int i = 0; i < nums.length; i++){
if(redCount > 0){
nums[i] = 0;
redCount--;
}else if(whiteCount > 0){
nums[i] = 1;
whiteCount--;
}else {
nums[i] = 2;
}
}
}
}

public class Solution {
/**
*双指针 一个redPos, 一个bluePos
*/
public void sortColors(int[] nums) {
if(nums == null || nums.length == 0)
return ;

int redPos = 0, bluePos = nums.length-1;
int i = 0;
while(i <= bluePos){
if(nums[i] == 0){
//0交换回来的只能是1 所以直接加
swap(nums, redPos, i);
redPos++;
}else if(nums[i] == 2){
//2交换回来的可能是0 所以要继续判断
swap(nums, bluePos, i);
bluePos--;
continue;
}

i++;
}
}

public void swap(int[] nums, int i, int j){
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}

• 本文已收录于以下专栏：

举报原因： 您举报文章：Sorts Colors 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)