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.

注意

You are not suppose to use the library's sort function for this problem.

样例

GIven colors=[3, 2, 2, 1, 4], k=4, your code should sort colors in-place to [1, 2, 2, 3, 4].

挑战

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?

SOLUTION 1:

使用快排,时间复杂度是O(nlogn),空间复杂度是O(Log(N))

 /**
* @param colors: A list of integer
* @param k: An integer
* @return: nothing
*/
/*
Solution 1: Using the quick sort.
*/
public void sortKColors1(int[] colors, int k) {
// write your code here
if (colors == null) {
return;
} quickSort(colors, , colors.length - );
} public void quickSort(int[] colors, int left, int right) {
if (left >= right) {
return;
} int pivot = colors[right]; int pos = partition(colors, left, right, pivot); quickSort(colors, left, pos - );
quickSort(colors, pos + , right);
} public int partition(int[] colors, int left, int right, int pivot) {
int leftPoint = left - ;
int rightPoint = right; while (true) {
while (colors[++leftPoint] < pivot); while (leftPoint < rightPoint && colors[--rightPoint] > pivot); if (leftPoint >= rightPoint) {
break;
} swap(colors, leftPoint, rightPoint);
} swap(colors, leftPoint, right);
return leftPoint;
} public void swap(int[] colors, int left, int right) {
int tmp = colors[left];
colors[left] = colors[right];
colors[right] = tmp;
}

SOLUTION 2:

inplace,并且O(N)时间复杂度的算法。

我们可以使用类似桶排序的思想,对所有的数进行计数。

1. 从左扫描到右边,遇到一个数字,先找到对应的bucket.比如

3 2 2 1 4

第一个3对应的bucket是index = 2 (bucket从0开始计算)

2. Bucket 如果有数字,则把这个数字移动到i的position(就是存放起来),然后把bucket记为-1(表示该位置是一个计数器,计1)。

3. Bucket 存的是负数,表示这个bucket已经是计数器,直接减1. 并把color[i] 设置为0 (表示此处已经计算过)

4. Bucket 存的是0,与3一样处理,将bucket设置为-1, 并把color[i] 设置为0 (表示此处已经计算过)

5. 回到position i,再判断此处是否为0(只要不是为0,就一直重复2-4的步骤)。

6.完成1-5的步骤后,从尾部到头部将数组置结果。(从尾至头是为了避免开头的计数器被覆盖)

例子(按以上步骤运算):

3 2 2 1 4

2 2 -1 1 4

2 -1 -1 1 4

0 -2 -1 1 4

-1 -2 -1 0 4

-1 -2 -1 -1 0

 // Solution 2: inplace, O(n)
public void sortKColors(int[] colors, int k) {
// write your code here
if (colors == null) {
return;
} int len = colors.length;
for (int i = ; i < len; i++) {
// Means need to deal with A[i]
while (colors[i] > ) {
int num = colors[i];
if (colors[num - ] > ) {
// 1. There is a number in the bucket,
// Store the number in the bucket in position i;
colors[i] = colors[num - ];
colors[num - ] = -;
} else if (colors[num - ] <= ) {
// 2. Bucket is using or the bucket is empty.
colors[num - ]--;
// delete the A[i];
colors[i] = ;
}
}
} int index = len - ;
for (int i = k - ; i >= ; i--) {
int cnt = -colors[i]; // Empty number.
if (cnt == ) {
continue;
} while (cnt > ) {
colors[index--] = i + ;
cnt--;
}
}

GITHUB:

https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/lintcode/array/SortKColors.java

Lintcode: Sort Colors II 解题报告的更多相关文章

  1. Lintcode: Sort Colors II

    Given an array of n objects with k different colors (numbered from 1 to k), sort them so that object ...

  2. Lintcode: Majority Number II 解题报告

    Majority Number II 原题链接: http://lintcode.com/en/problem/majority-number-ii/# Given an array of integ ...

  3. 【LeetCode】Pascal's Triangle II 解题报告

    [LeetCode]Pascal's Triangle II 解题报告 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problems/pascals-tr ...

  4. 【LeetCode】375. Guess Number Higher or Lower II 解题报告(Python)

    [LeetCode]375. Guess Number Higher or Lower II 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://f ...

  5. 【LeetCode】731. My Calendar II 解题报告(Python)

    [LeetCode]731. My Calendar II 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题 ...

  6. 【LeetCode】522. Longest Uncommon Subsequence II 解题报告(Python)

    [LeetCode]522. Longest Uncommon Subsequence II 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemin ...

  7. 【LeetCode】117. Populating Next Right Pointers in Each Node II 解题报告(Python)

    [LeetCode]117. Populating Next Right Pointers in Each Node II 解题报告(Python) 标签: LeetCode 题目地址:https:/ ...

  8. 【LeetCode】137. Single Number II 解题报告(Python)

    [LeetCode]137. Single Number II 解题报告(Python) 标签: LeetCode 题目地址:https://leetcode.com/problems/single- ...

  9. 【LeetCode】154. Find Minimum in Rotated Sorted Array II 解题报告(Python)

    [LeetCode]154. Find Minimum in Rotated Sorted Array II 解题报告(Python) 标签: LeetCode 题目地址:https://leetco ...

随机推荐

  1. maven常见问题问答(转)

    转自:http://www.oschina.net/question/158170_29368 1.前言 Maven,发音是[`meivin],"专家"的 意思.它是一个很好的项目 ...

  2. java hibernate session create

    public class RegisterStory { private SysUserCDao sysUserCDao; @Test public void test() { SessionFact ...

  3. lu协程练习

    生产者和消费者问题:当协程调用yield时,从一个悬而未决的resume中返回.简单的协程练习: function receive() local status,value = coroutine.r ...

  4. 查看linux设备文件系统类型的方法

    网络上找来找去没有找到简单的,最后翻了鸟哥的书就找到了,鸟哥的书还是真的有用心写的. /proc/filesystems 当前被内核支持的文件系统类型列表文件 /etc/filesystems 系统已 ...

  5. iscsi target 研究

    一.概述 目前 Linux 上主要有三个 iSCSI Target 实现: Linux SCSI Target – STGT / tgt     Linux-IO Target – LIO SCST ...

  6. <welcome-file>index.action</welcome-file>直接设置action,404和struts2中的解决方案

    这几天的项目页面的访问全部改为.action访问,在修改首页时遇到了问题.将web.xml文件中<welcome-file>index.action</welcome-file> ...

  7. linux arm的高端内存映射

    linux arm的高端内存映射(1) vmalloc 高端内存映射   与高端映射对立的是低端映射或所谓直接映射,内核中有关变量定义它们的它们的分界点,全局变量high_memory,该变量定义在m ...

  8. appium简明教程(5)——appium client方法一览

    appium client扩展了原生的webdriver client方法 下面以java代码为例,简单过一下appium client提供的适合移动端使用的新方法 resetApp() getApp ...

  9. Python 文件 close() 方法

    描述 Python 文件 close() 方法用于关闭一个已打开的文件.关闭后的文件不能再进行读写操作, 否则会触发 ValueError 错误. close() 方法允许调用多次. 当 file 对 ...

  10. java播放wav文件

    import java.io.File; import java.io.IOException; import javax.sound.sampled.AudioFormat; import java ...