排颜色 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);
    }
}
Java Code

相关文章:

  • 2021-09-07
  • 2021-11-28
  • 2022-12-23
  • 2021-12-29
  • 2022-12-23
  • 2021-08-08
  • 2021-10-10
猜你喜欢
  • 2021-09-17
  • 2022-01-18
  • 2021-07-15
  • 2021-06-25
  • 2021-11-14
  • 2021-06-05
相关资源
相似解决方案