描述
给定一个有n个对象(包括k种不同的颜色,并按照1到k进行编号)的数组,将对象进行分类使相同颜色的对象相邻,并按照1,2,...k的顺序进行排序。
不能使用代码库中的排序函数来解决这个问题
k <= n
样例
样例1
输入:
[3,2,2,1,4]
4
输出:
[1,2,2,3,4]
样例2
输入:
[2,1,1,2,2]
2
输出:
[1,1,2,2,2]
publicclassSolution{/**
* @param colors: A list of integer
* @param k: An integer
* @return: nothing
*/publicvoidsortColors2(int[] colors,int k){// write your code hereif(colors.length ==0){return;}sort(colors,0, colors.length -1,1, k);}privatevoidsort(int[] nums,int start,int end,int cStart,int cEnd){if(start > end || cStart >= cEnd){return;}int mid =(cStart + cEnd)/2;int l = start, r = end;while(l < r){while(l < r && nums[r]> mid){
r--;}while(l < r && nums[l]<= mid){
l++;}if(l < r){int tmp = nums[l];
nums[l]= nums[r];
nums[r]= tmp;
l++;
r--;}}sort(nums, start, l, cStart, mid);sort(nums, r, end, mid +1, cEnd);}}
publicclassSolution{/**
* @param colors: A list of integer
* @param k: An integer
* @return: nothing
*/publicvoidsortColors2(int[] colors,int k){// write your code hereif(colors.length ==0){return;}sort(colors,0, colors.length -1,1, k);}privatevoidsort(int[] nums,int start,int end,int cStart,int cEnd){if(start >= end || cStart >= cEnd){return;}int mid =(cStart + cEnd)/2;int l = start, r = end;while(l <= r){while(l <= r && nums[r]> mid){
r--;}while(l <= r && nums[l]<= mid){
l++;}if(l <= r){int tmp = nums[l];
nums[l]= nums[r];
nums[r]= tmp;
l++;
r--;}}sort(nums, start, r, cStart, mid);sort(nums, l, end, mid +1, cEnd);}}
publicclassSolution{/**
* @param colors: A list of integer
* @param k: An integer
* @return: nothing
*/publicvoidsortColors2(int[] colors,int k){// write your code hereint bucket[]=newint[k +1];for(int i =0; i < colors.length; i++){
bucket[colors[i]]++;}int cur =0;for(int i =0; i < bucket.length; i++){while(bucket[i]!=0){
colors[cur++]= i;
bucket[i]--;}}}}