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

lintcode-medium-Sort Colors II

时间:2016-04-06 08:10:50      阅读:189      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!