一、问题描述
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.
二、问题分析
利用两个计数器,红球计数器从前往后走,蓝球计数器从后往前走。
三、算法代码
public class Solution {
public void sortColors(int[] nums) {
int red = 0;
int blue = nums.length - 1;
int tmp = -1;
for(int i = 0; i < blue + 1; ){
if(nums[i] == 0){
tmp = nums[red];
nums[red] = nums[i];
nums[i] = tmp;
red++;
i++;
}else if(nums[i] == 2){
tmp = nums[i];
nums[i] = nums[blue]; //当找到蓝球时,计数器i值要保持不变
nums[blue] = tmp;
blue--;
}else{
i++;
}
}
}
}