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 ...
随机推荐
- Cobbler的Web管理和维护
Cobbler的Web管理模块和命令行模块是可以分开工作的,没有依赖关系. 1 WebUI的功能 查看所有的对象和配置文件 添加或者删除system,distro, profile 执行“cobble ...
- [转]nf_conntrack: table full, dropping packet 连接跟踪表已满,开始丢包 的解决办法
nf_conntrack: table full, dropping packet 连接跟踪表已满,开始丢包 的解决办法 中午业务说机器不能登录,我通过USM管理界面登录单板的时候发现机器没有僵 ...
- js跨域问题解释 使用jsonp或jQuery的解决方案
js跨域及解决方案 1.什么是跨域 我们经常会在页面上使用ajax请求访问其他服务器的数据,此时,客户端会出现跨域问题. 跨域问题是由于javascript语言安全限制中的同源策略造成的. 简单来说, ...
- C语言学习笔记 (010) - 编写strcpy函数
很多公司的面试官在面试程序员的时候,要求应聘者写出库函数strcpy()的工作方式或者叫实现,很多人以为这个题目很简单,实则不然,别看这么一个小小的函数,它可以从三个方面来考查: (1)编程风格 (2 ...
- ML之监督学习算法之分类算法一 ———— k-近邻算法(最邻近算法)
一.概述 最近邻规则分类(K-Nearest Neighbor)KNN算法 由Cover 和Hart在1968年提出了最初的邻近算法, 这是一个分类(classification)算法 输入基于实例的 ...
- 代码管理(五)git 删除分支
1.删除远程分支 在远程下面,选择需要删除的分支,右击,选择删除 2. 删除不存在远程对应分支的本地分支 在远程上建立了一个分支feature,后来leader觉得不合理,就把远程feature分支 ...
- ios开发中用过的一些外部库总结 cocoapods list
下面几个库是在之前的一个ios app开发中使用过的一些外部库: 1. zbar :2. shakebox :3. processbar :4. tableviewcontroller :新版的sta ...
- java中的switch case default break
package com.didispace; /** * Created by gmq on 2017/08/07. * * @version 1.0 * @since 2017/08/07 10:4 ...
- 10个优秀的jQuery Mobile主题
原文链接:http://caibaojian.com/10-best-free-jquery-mobile-theme.html jQuery Mobile 是一个伟大的框架,而每个伟大的产品都需要一 ...
- Mysql:MyIsam和InnoDB的区别
MyISAM: 这个是默认类型,它是基于传统的ISAM类型,ISAM是Indexed Sequential Access Method (有索引的 顺序访问方法) 的缩写,它是存储记录和文件的标准方法 ...