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 ...
随机推荐
- 【DeepLearning】UFLDL tutorial错误记录
(一)Autoencoders and Sparsity章节公式错误: s2 应为 s3. 意为从第2层(隐藏层)i节点到输出层j节点的误差加权和. (二)Support functions for ...
- php使用wkhtmltopdf导出pdf
参考:史上最强php生成pdf文件,html转pdf文件方法 http://biostall.com/wkhtmltopdf-add-header-footer-to-only-first-last- ...
- 基于matplotlib的数据可视化 - 柱状图bar
柱状图bar 柱状图常用表现形式为: plt.bar(水平坐标数组,高度数组,宽度比例,ec=勾边色,c=填充色,label=图例标签) 注:当高度值为负数时,柱形向下 1 语法 bar(*args, ...
- 《JAVA与模式》之简单工厂与工厂方法
一.简单工厂 1.1 使用场景 1.工厂类负责创建的对象比较少: 2.客户只知道传入工厂类的参数,对于如何创建对象(逻辑)不关心: 3.由于简单工厂很容易违反高内聚责任分配原则,因此一般只在很简单的情 ...
- C++中没有finally,那么应该在哪里关闭资源?
这是一篇有趣的帖子 原文链接: http://bbs.csdn.net/topics/90070457 楼主: C++中没有finally,那么应该在哪里关闭资源? C++的try{}catch(){ ...
- C# 创建windows 服务
1. 新建项目 1.1 右键解决方案 – 添加 – 新建项目 1.2 已安装模板 - windows - windows服务 – 输入名称 – 点击 ”确定” 2. 添加相应的 ...
- 增量式pid和位置式PID参数整定过程对比
//增量式PID float IncPIDCalc(PID_Typedef* PIDx,float SetValue,float MeaValue)//err»ý·Ö·ÖÀë³£Êý { PIDx-& ...
- [转]@PathVariable和@RequestParam的区别
请求路径上有个id的变量值,可以通过@PathVariable来获取 @RequestMapping(value = "/page/{id}", method = Request ...
- Android系统版本与API级别对照表
对照表 API Level 最初Android版本 Linux内核版本 首次发布日期 后续Android版本 28 9 Unknown 2018-07-02(Beta 3) - 27 8.1 4.10 ...
- zTree变异篇:如何让同级树节点平铺而非垂直显示
昨天有一个zTree的使用者在实际的项目中有着这样一个特殊的需求,要求同级树节点能够水平显示,根据设定的宽度自动换行,效果图如下所示: 通过在浏览器调试模式下观察其同级节点的css为: 这个dis ...