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.
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 解题报告的更多相关文章
- Lintcode: Sort Colors II
Given an array of n objects with k different colors (numbered from 1 to k), sort them so that object ...
- Lintcode: Majority Number II 解题报告
Majority Number II 原题链接: http://lintcode.com/en/problem/majority-number-ii/# Given an array of integ ...
- 【LeetCode】Pascal's Triangle II 解题报告
[LeetCode]Pascal's Triangle II 解题报告 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problems/pascals-tr ...
- 【LeetCode】375. Guess Number Higher or Lower II 解题报告(Python)
[LeetCode]375. Guess Number Higher or Lower II 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://f ...
- 【LeetCode】731. My Calendar II 解题报告(Python)
[LeetCode]731. My Calendar II 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题 ...
- 【LeetCode】522. Longest Uncommon Subsequence II 解题报告(Python)
[LeetCode]522. Longest Uncommon Subsequence II 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemin ...
- 【LeetCode】117. Populating Next Right Pointers in Each Node II 解题报告(Python)
[LeetCode]117. Populating Next Right Pointers in Each Node II 解题报告(Python) 标签: LeetCode 题目地址:https:/ ...
- 【LeetCode】137. Single Number II 解题报告(Python)
[LeetCode]137. Single Number II 解题报告(Python) 标签: LeetCode 题目地址:https://leetcode.com/problems/single- ...
- 【LeetCode】154. Find Minimum in Rotated Sorted Array II 解题报告(Python)
[LeetCode]154. Find Minimum in Rotated Sorted Array II 解题报告(Python) 标签: LeetCode 题目地址:https://leetco ...
随机推荐
- 定制jQuery File Upload为微博式单文件上传
日志未经声明,均为AlloVince原创.版权采用『 知识共享署名-非商业性使用 2.5 许可协议』进行许可. jQuery File Upload是一个非常优秀的上传组件,主要使用了XHR作为上传方 ...
- Linux中断的系统调用
早期UNIX系统的一个特性是:如果在进程执行一个低速系统调用而阻塞期间捕捉到一个信号,则该系统调用就被中断不再继续执行.该系统调用返回出错,其errno设置为EINTR.这样处理的理由是:因为一个信号 ...
- 8.翻译:EF基础系列----EF中实体的状态
原文链接:http://www.entityframeworktutorial.net/basics/entity-states.aspx 在实体的生命周期中,EF API维护着每一个实体的状态,对于 ...
- python pandas replace函数
在处理数据的时候,很多时候会遇到批量替换的情况,如果一个一个去修改效率过低,也容易出错.replace()是很好的方法. 1.基本结构: df.replace(to_replace, value) 前 ...
- php实现ZIP压缩文件解压缩(转)
测试使用了两个办法都可以实现: 第一个:需要开启配置php_aip.dll <?php //需开启配置 php_zip.dll //phpinfo(); header("Content ...
- jmeter压测前清理内存
jmeter 压测时设置了内存为sed -i 's/HEAP="-Xms512m -Xmx512m"/HEAP="-Xms36096m -Xmx360096m" ...
- Axure chrome 扩展显示已损坏的解决方法
下载地址 链接:https://pan.baidu.com/s/11K3t_mvgJg51siO_jNRejg 提取码:goz1 如果链接失效,请留言或站内信提醒我更新 疑问 之前用的好好的Axure ...
- RSA算法 JS加密 JAVA解密
有这样一个需求,前端登录的usernamepassword,password必需加密.但不可使用MD5,由于后台要检測password的复杂度,那么在保证安全的前提下将password传到后台呢,答案 ...
- collections集合的总括。
序言 突然遇到集合的有关面试题,感觉很懵逼,所以特意总结了一下,关于我们常用的 ArrayList.LinkedList.Set等集合的一些区别和用法. 还有,这份微小型总结肯定是从很多博文中摘取精华 ...
- 基于Xilinx Zynq Z7045 SoC的CNN的视觉识别应用
基于Xilinx Zynq Z7045 SoC的CNN的视觉识别应用 由 judyzhong 于 星期三, 08/16/2017 - 14:56 发表 作者:stark 近些年来随着科学技术的不断进步 ...