Sort Colors II Lintcode

Posted 璨璨要好好学习

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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

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的主要内容,如果未能解决你的问题,请参考以下文章

lintcode143 - Sort Colors II - medium

lintcode-medium-Sort Colors

lintcode:排颜色 II

[LintCode] Sort Integers II 整数排序之二

3 - Two Pointers Algorithm

Sort colors系列