首页 > 其他 > 详细

lintcode-medium-Sort Colors II

时间:2016-04-06 08:10:48      阅读:175      评论:0      收藏:0      [点我收藏+]

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.

 

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?

 

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
        
        if(colors == null || colors.length == 0)
            return;
        
        int start = 0;
        int end = colors.length - 1;
        int count = 0;
        
        while(count < k){
            int left = start;
            int right = end;
            
            int max = Integer.MIN_VALUE;
            int min = Integer.MAX_VALUE;
            
            for(int i = start; i <= end; i++){
                max = Math.max(max, colors[i]);
                min = Math.min(min, colors[i]);
            }
            
            while(left < right && colors[left] == min)
                left++;
            while(left < right && colors[right] == max)
                right--;
            
            int i = left;
            
            while(i <= right){
                if(colors[i] == min){
                    swap(colors, i, left);
                    left++;
                    
                    while(left < right && colors[left] == min)
                        left++;
                    
                    i = left;
                }
                else if(colors[i] == max){
                    swap(colors, i, right);
                    right--;
                    
                    while(left < right && colors[right] == max)
                        right--;
                }
                else{
                    i++;
                }
            }
            
            start = left;
            end = right;
            count += 2;
        }
        
        return;
    }
    
    public void swap(int[] nums, int i, int j){
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
        
        return;
    }
}

 

lintcode-medium-Sort Colors II

原文:http://www.cnblogs.com/goblinengineer/p/5357692.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!