lintcode-medium-Sort Colors II

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;
    }
}

 

posted @ 2016-04-06 07:26  哥布林工程师  阅读(125)  评论(0编辑  收藏  举报