颜色分类 II Sort Colors II
Description
Given an array of n objects with k different colors (numbered from 1 to k), sort them so that objects of the same color are adjacent, with the colors in the order 1, 2, … k.
public class Solution {
/**
* @param colors: A list of integer
* @param k: An integer
* @return: nothing
*/
public void sortColors2(int[] colors, int k) {
// write your code here
if(colors == null || colors.length == 0){
return ;
}
rainbowSort(colors , 0 , colors.length-1 , 1 , k) ;
}
public void rainbowSort(int[] colors , int start , int end , int colorForm , int colorTo){
if(colorForm == colorTo){
return ;
}
if(start >= end){
return ;
}
int colorMid = colorForm + (colorTo - colorForm) / 2 ;
int left = start , right = end ;
while(left <= right){
while(left <= right && colors[left] <= colorMid){
left++ ;
}
while(left <= right && colors[right] > colorMid){
right-- ;
}
if(left <= right){
int temp = colors[left] ;
colors[left] = colors[right] ;
colors[right] = temp ;
left++ ;
right-- ;
}
}
rainbowSort(colors , start , right , colorForm , colorMid) ;
rainbowSort(colors , left , end , colorMid+1 , colorTo) ;
}
}