码迷,mamicode.com
首页 > 其他好文 > 详细

Sort Colors II Lintcode

时间:2017-04-06 10:04:51      阅读:221      评论:0      收藏:0      [点我收藏+]

标签:code   pos   rar   com   span   ber   function   oid   lap   

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

标签:code   pos   rar   com   span   ber   function   oid   lap   

原文地址:http://www.cnblogs.com/aprilyang/p/6671425.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!