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. Java6 WebService的发布(转)

      Java6 WebService的发布   转:http://lavasoft.blog.51cto.com/62575/227988/   WebService服务发布往往比较混乱,Axis2的 ...

  2. vim自动缩进设置

    需要软件 vim 下载地址 http://www.vim.org   code_complete.vim 插件 http://www.vim.org/scripts/script.php?script ...

  3. Redis 启动警告错误解决[转]

    Redis 启动警告错误解决 启动错误 1.WARNING overcommit_memory is set to 0! Background save may fail under low memo ...

  4. 【C语言】练习5-8

     题目来源:<The C programming language>中的习题P92  练习5-8: 一个日期转换的问题,把某月某日这种日期表示形式转换为某年中第几天的表示形式,反之亦然.例 ...

  5. 那些令人喷饭的代码注释:仅以此代码献给...it's realy ?

    程序源代码中的注释经常是一个卧虎藏龙的地方,有人就很喜欢写幽默搞笑的注释内容.解释代码含义的同时,也带给人轻松神经的机会,确实是很有意思的风格,来看看这一辑国外某公司产品中的注释. 注意:看的时候严禁 ...

  6. python 生成图表

    python写入excel(xlswriter)--生成图表 折线图 # -*- coding:utf-8 -*- import xlsxwriter # 创建一个excel workbook = x ...

  7. 近期对招聘Android开发者的一些思考

    公司要招聘Android开发者,故面试了大概十来个人.由于是小公司,所以来的人大多是90后,比較年轻.90后大概二十三四岁吧,从简历上看都写了一到两年的工作经验. 也由于是小公司,所以对工作经验这些没 ...

  8. Sublime text —— 自定义主题Soda

    编辑器的主题有两种,一种是语法高亮颜色主题,一种是编辑器自身显示主题,如果要自定义编辑器样式,个人推荐soda. Ctrl+Shift+p 输入install,接着输入  soda,选择  Theme ...

  9. 目标检测 的标注数据 .xml 转为 tfrecord 的格式用于 TensorFlow 训练

    将目标检测 的标注数据 .xml 转为 tfrecord 的格式用于 TensorFlow 训练. import xml.etree.ElementTree as ET import numpy as ...

  10. git 放弃本地修改(转)

    如果在修改时发现修改错误,而要放弃本地修改时, 一, 未使用 git add 缓存代码时. 可以使用 git checkout -- filepathname (比如: git checkout -- ...