lintcode143 - Sort Colors II - medium

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?
Notice
You are not suppose to use the library‘s sort function for this problem.
k <= n

1.O(nk)方法。
每一轮,扫描一次找到最小色和最大色,再扫描一次把最小色放到left++,最大色放到right—。
重复k/2轮就排好了

2.O(nlogk)方法,极限。
快排思想的递归。每次把中间颜色都放到最中间那块地盘,保证左边的都是比中间色小的,右边的都是比中间色大的,左右两块内部顺序随意,之后递归排着。每一次扫描一整遍O(n),一共要这样调用logk层。因为每次是对颜色这个对象二分规模,所以是logk。
每一轮具体也是两根指针往中间缩,left指到不合格的>mid的对象,right指到不合格的<=mid的对象,就停下来互换。
细节:
1.因为midColor=()/2是不对称的,会偏小,所以对比colors[left] colors[right]和midColor也不对称。想最极端的只有两色12的情况,mid是1,left要指到2这种>1的才能停,right要指到<=1的都要停。上面加=减=你试试就知道都不行,要么把位置对的换走了,要么根本指不到。
2.要解决已经排好序了从头到位只有一根指针在移动的情况,也就是把n个元素进一步分为n个的组和0个的组,那你再递归下去就死循环了。所以如果发现有一根指针没动过,那就不继续递归了。

1.O(nk)实现

public 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

        int left = 0, right = colors.length - 1;
        int count = 0;
        while (count < k) {
            int min = k, max = 1;
            for (int i = left; i <= right; i++) {
                min = Math.min(min, colors[i]);
                max = Math.max(max, colors[i]);
            }
            int ptr = left;
            while (ptr <= right) {
                if (colors[ptr] == min) {
                    swap(colors, left, ptr);
                    left++;
                    ptr++;
                } else if (colors[ptr] == max) {
                    swap(colors, right, ptr);
                    right--;
                } else {
                    ptr++;
                }
            }
            count+=2;
        }
    }

    private void swap(int[] colors, int i, int j) {
        int temp = colors[i];
        colors[i] = colors[j];
        colors[j] = temp;
    }
}

2.O(nlogk)实现

public 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;
        }
        partitionColors(colors, 0, colors.length - 1, 1, k);
    }

    private void partitionColors(int[] colors, int start, int end, int startColor, int endColor) {

        if (start >= end || startColor >= endColor) {
            return;
        }

        int left = start, right = end;
        int midColor = (startColor + endColor) / 2;
        while (left < right) {
            // 注意不是<,因为mid求的时候有偏小。写错对只有两色的情况如21122就会把正确的1换走了
            while (left < right && colors[left] <= midColor) {
                left++;
            }
            while (left < right && colors[right] > midColor) {
                right--;
            }
            if (left < right) {
                int temp = colors[left];
                colors[left] = colors[right];
                colors[right] = temp;
                left++;
                right--;
            }
        }
        if (start == left || end == right) {
            return;
        }
        partitionColors(colors, start, right, startColor, midColor);
        partitionColors(colors, left, end, midColor, endColor);
    }
}

原文地址:https://www.cnblogs.com/jasminemzy/p/9552188.html

时间: 2024-10-30 04:28:32

lintcode143 - Sort Colors II - medium的相关文章

Lintcode: Sort Colors II 解题报告

Sort Colors II 原题链接: http://lintcode.com/zh-cn/problem/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. 注意

Sort Colors II Lintcode

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 pro

[leetcode] 040. Combination Sum II (Medium) (C++)

索引:[LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql) Github: https://github.com/illuz/leetcode 040. Combination Sum II (Medium) 链接: 题目:https://leetcode.com/problems/combination-sum-ii/ 代码(github):https://github.com/illuz/leetcode 题意: 跟 039 一样(给出一些正整数集合,

[array] leetcode - 40. Combination Sum II - Medium

leetcode - 40. Combination Sum II - Medium descrition Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. Each number in C may only be used once in the combinat

LeetCode 75. 颜色分类(Sort Colors) 30

75. 颜色分类 75. Sort Colors 题目描述 给定一个包含红色.白色和蓝色,一共 n 个元素的数组,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色.白色.蓝色顺序排列. 此题中,我们使用整数 0. 1 和 2 分别表示红色.白色和蓝色. 注意: 不能使用代码库中的排序函数来解决这道题. 每日一算法2019/6/2Day 30LeetCode75. Sort Colors 示例: 输入: [2,0,2,1,1,0] 输出: [0,0,1,1,2,2] 进阶: 一个直观的解决方

刷题75. Sort Colors

一.题目说明 题目75. Sort Colors,给定n个整数的列表(0代表red,1代表white,2代表blue),排序实现相同颜色在一起.难度是Medium. 二.我的解答 这个是一个排序,还是简单的,代码如下: class Solution{ public: void sortColors(vector<int>& nums){ int num0=0,num1=0,num2=0; for(int i=0;i<nums.size();i++){ if(nums[i]==0)

Sort colors系列

75. Sort Colors 问题描述: 给一个包含n个数字的数组,其中有0,1,2:排序使得所有相同的数字相邻,且按照0,1,2的顺序. 思路: (1)计数排序: 需要扫两遍数组,一遍统计个数,第二遍开始摆放数字. 代码如下: 1 void sortColors(vector<int>& nums) { 2 int i=0,j=0,k=0; 3 int n=nums.size(); 4 for(int p=0;p<n;p++) 5 { 6 if(nums[p]==0) 7 i

leetcode Sort Colors

*/--> pre.src {background-color: Black; color: White;} pre.src {background-color: Black; color: White;} pre.src {background-color: Black; color: White;} leetcode Sort Colors 计数排序 注: 题目的要求是将 A 数组重新排列成有序, 而不是将排序的序列输出 Sort Colors Given an array with n o

【LeetCode】Sort Colors

LeetCode OJ Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue. Here, we will use the integers 0, 1, and 2 to represent the color red, w