排颜色 II
给定一个有n个对象(包括k种不同的颜色,并按照1到k进行编号)的数组,将对象进行分类使相同颜色的对象相邻,并按照1,2,...k的顺序进行排序。
样例
给出colors=[3, 2, 2, 1, 4],k=4, 你的代码应该在原地操作使得数组变成[1, 2, 2, 3, 4]
解题
直接快排
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 sort(colors,0,colors.length - 1); } public void sort(int[] A,int low,int high){ if(low >= high) return ; int i = low; int j = high; int tmp = A[low]; while(i<j){ while(i<j && A[j]>tmp) j--; if(i<j){ A[i] = A[j]; i++; } while(i<j && A[i]<= tmp) i++; if(i<j){ A[j] = A[i]; j--; } } A[i] = tmp; sort(A,low,i-1); sort(A,i+1,high); } }