lintcode-medium-Sort Colors II

Posted 哥布林工程师

tags:

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

 

以上是关于lintcode-medium-Sort Colors II的主要内容,如果未能解决你的问题,请参考以下文章

lintcode-medium-Sort Colors II

lintcode-medium-Sort Letters by Case

用于早期 Web 应用的虚拟专用服务器托管与 Colo + 自己的服务器

html 用于检查产品是否具有Colo(u)r选项且可用多种颜色的脚本。

路翼colo-rc蓝牙为什么搜索不到

wwbt3