[LintCode]Sort Colors II

http://www.lintcode.com/en/problem/sort-colors-ii/

一共k種顏色,進行排序




快排思想,找到fromColor到toColor的中點mid,將colors分爲小於等於mid的和大於mid的兩個部分,然後遞歸排序

class Solution {
    public void sortColors2(int[] colors, int k) {
        // write your code here
        qSort(colors, 0, colors.length - 1, 1, k);
    }
    private void qSort(int[] colors, int left, int right, int fromCol, int toCol) {
        if (left >= right) {
            return;
        }
        if (fromCol >= toCol) {
            return;
        }
        int mid = fromCol + (toCol - fromCol) / 2;
        int beg = left;
        int end = right;
        while (beg <= end) {
            while (beg <= end && colors[beg] <= mid) {
                beg++;
            }
            while (beg <= end && colors[end] > mid) {
                end--;
            }
            if (beg <= end) {
                int temp = colors[beg];
                colors[beg] = colors[end];
                colors[end] = temp;
                beg++;
                end--;
            }
        }
        qSort(colors, left, end, fromCol, mid);
        qSort(colors, beg, right, mid + 1, toCol);
    }
}


發佈了363 篇原創文章 · 獲贊 1 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章