首页 > 代码库 > Sort Colors II Lintcode

Sort Colors II Lintcode

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.

 Notice

You are not suppose to use the library‘s sort function for this problem.

k <= n

Have you met this question in a real interview? 
Yes
Example

Given colors=[3, 2, 2, 1, 4]k=4, your code should sort colors in-place to [1, 2, 2, 3, 4].

Challenge 

A rather straight forward solution is a two-pass algorithm using counting sort. That will cost O(k) extra memory. Can you do it without using extra memory?

这道题其实是quick sort的变形,加深了对quick sort的理解,计算时间复杂的的时候,时间复杂度是nlogk.

class Solution {
    /**
     * @param colors: A list of integer
     * @param k: An integer
     * @return: nothing
     */
    public void sortColors2(int[] colors, int k) {
        int left = 0;
        int right = colors.length - 1;
        helper(colors, left, right, 1, k);
    }
    private void helper(int[] colors, int l, int r, int from, int to) {
        if (from == to) {
            return;
        }
        if (l >= r) {
            return;
        }
        int left = l;
        int right = r;
        int mid = (to - from) / 2 + from;
        while (left < right) {
            while (left < right && colors[left] <= mid) {
                left++;
            }
            while (left < right && colors[right] > mid) {
                right--;
            }
            swap(colors, left, right);
        }
        helper(colors, l, right, from, mid);
        helper(colors, left, r, mid + 1, to);
    }
    private void swap(int[] colors, int left, int right) {
        int tmp = colors[left];
        colors[left] = colors[right];
        colors[right] = tmp;
    }
}

 

 
 

Sort Colors II Lintcode