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.

Note
You are not suppose to use the library's sort function for this problem. Example
GIven colors=[3, 2, 2, 1, 4], k=4, your code should sort colors in-place to [1, 2, 2, 3, 4]. Challenge
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?

先写了个O(kN)时间复杂度,O(1)空间复杂度的, 这个算法适合颜色数比较少的情况(k is constant)

 class Solution {
/**
* @param colors: A list of integer
* @param k: An integer
* @return: nothing
*/
public void sortColors2(int[] colors, int k) {
// write your code here
if (colors==null || colors.length==0 || k<=1) return;
int l=0, r=colors.length-1;
int cnt = 1;
for (; cnt<k; cnt++) {
while (true) {
while (l<r && colors[l]==cnt) {
l++;
}
while (l<r && colors[r]!=cnt) {
r--;
}
if (l == r) break;
swap(colors, l, r);
}
r = colors.length-1;
if (l == r) break;
}
} public void swap(int[] colors, int l, int r) {
int temp = colors[l];
colors[l] = colors[r];
colors[r] = temp;
}
}

K->N的话,上面时间复杂度就大了,所以干脆用Quick Sort

 class Solution {
/**
* @param colors: A list of integer
* @param k: An integer
* @return: nothing
*/
public void sortColors2(int[] colors, int k) {
// write your code here
if (colors==null || colors.length==0 || k<=1) return;
quickSort(colors, 0, colors.length-1);
} public void quickSort(int[] colors, int l, int r) {
if (l >= r) return;
int pivot = r;
int pos = partition(colors, l, r, pivot);
quickSort(colors, l, pos-1);
quickSort(colors, pos+1, r);
} public int partition(int[] colors, int start, int end, int pivot) {
int l=start, r=end;
while (true) {
while (l<r && colors[l]<colors[pivot]) {
l++;
}
while (l<r && colors[r]>=colors[pivot]) {
r--;
}
if (l == r) break;
swap(colors, l, r);
}
swap(colors, l, end);
return l;
} public void swap(int[] colors, int l, int r) {
int temp = colors[l];
colors[l] = colors[r];
colors[r] = temp;
}
}

有人给出了O(N)的解法(better solution)

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

O(n): use the array itself as space to store counts. We use A[k-1] to store the count of color k. We use negtive number to store count, in order to be distnct with the color value. This method ASSUMES that every color between 1 and k will appear.

At position i, if A[i] is positive, we check the value of A[A[i]-1], if it is a positive number, i.e., not counted yet, we then put A[A[i]-1] to A[i], and set A[A[i]-1] as -1 to indicate that there is one of this color.

If A[A[i]-1] is a negtive or zero value, we then simply decrease it by one and set A[i] as 0 to indicate that this position is couted already.

At position i, we repeat this procedure until A[i] becomes 0 or negtive, we then move to i+1.

At counting, we draw colors into array.

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

 class Solution {
/**
* @param colors: A list of integer
* @param k: An integer
* @return: nothing
*/
public void sortColors2(int[] colors, int k) {
//The method assumes that every color much appear in the array.
int len = colors.length;
if (len<k) return; //count the number of each color.
for (int i=0;i<len;i++){
while (colors[i]>0){
int key = colors[i]-1;
if (colors[key]<=0){
colors[key]--;
colors[i]=0;
}
else {
colors[i] = colors[key];
colors[key] = -1;
}
}
} //draw colors.
int index = len - 1;
for (int i = k - 1; i >= 0; i--) {
int cnt = -colors[i]; // Empty number.
if (cnt == 0) {
continue;
} while (cnt > 0) {
colors[index--] = i + 1;
cnt--;
}
}
}
}

若k事先不知道,一样的,就是开始维护一个counter, 在过程中算一下。

 class Solution {
/**
* @param colors: A list of integer
* @param k: An integer
* @return: nothing
*/
public void sortColors2(int[] colors) {
// write your code here
int len = colors.length; int count = 0;
for (int i=0; i<len; i++) {
while (colors[i] > 0) {
count++;
int pos = colors[i]-1; //最好搞个变量存一下,之后方便
if (colors[pos] > 0) {
colors[i] = colors[pos];
colors[pos] = -1;
}
else {
colors[pos]--;
colors[i] = 0;
}
}
} //sort
int index = colors.length-1;
for (int j=count; j>0; j--) {
int num = -colors[j-1];
while (num > 0) {
colors[index--] = j;
num--;
}
}
}
}

Lintcode: Sort Colors II的更多相关文章

  1. Lintcode: Sort Colors II 解题报告

    Sort Colors II 原题链接: http://lintcode.com/zh-cn/problem/sort-colors-ii/# Given an array of n objects ...

  2. LintCode Sort Colors

    For this problem we need to sort the array into three parts namely with three numbers standing for t ...

  3. [LintCode] Sort Integers II 整数排序之二

    Given an integer array, sort it in ascending order. Use quick sort, merge sort, heap sort or any O(n ...

  4. 143. Sort Colors II

    最后更新 一刷 class Solution { public void sortColors2(int[] colors, int k) { // write your code here if ( ...

  5. LeetCode: Sort Colors 解题报告

    Sort ColorsGiven an array with n objects colored red, white or blue, sort them so that objects of th ...

  6. Sort Colors I & II

    Given an array with n objects colored red, white or blue, sort them so that objects of the same colo ...

  7. lintcode:排颜色 II

    排颜色 II 给定一个有n个对象(包括k种不同的颜色,并按照1到k进行编号)的数组,将对象进行分类使相同颜色的对象相邻,并按照1,2,...k的顺序进行排序. 样例 给出colors=[3, 2, 2 ...

  8. LeetCode 75. 颜色分类(Sort Colors) 30

    75. 颜色分类 75. Sort Colors 题目描述 给定一个包含红色.白色和蓝色,一共 n 个元素的数组,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色.白色.蓝色顺序排列. 此题中, ...

  9. 【LeetCode】Sort Colors

    Sort Colors Given an array with n objects colored red, white or blue, sort them so that objects of t ...

随机推荐

  1. (转)Linux下安装Matlab2014及破解

    原文链接:http://blog.csdn.net/lanbing510/article/details/41698285 文章已搬家至http://lanbing510.info/2014/12/0 ...

  2. Apache的HBase与cdh的hue集成(不建议不同版本之间的集成)

    1.修改hue的配置文件hue.ini [hbase] # Use full hostname with security. hbase_clusters=(Cluster|linux-hadoop3 ...

  3. Qt 自定义 滚动条 样式(模仿QQ)

    今天是时候把软件中的进度条给美化美化了,最初的想法就是仿照QQ. 先前的进度条是这样,默认的总是很难受欢迎的:美化之后的是这样,怎么样?稍微好看一点点了吧,最后告诉你实现这个简单的效果在Qt只需要加几 ...

  4. 改变当前shell工作目录

    执行脚本时候,只是在当前的shell下开了一个子进程,切换目录的操作只对该进程中相关后续指令有效,但改变不了父进程的目录. 解决方法: 法一: 用 source a.sh就行了. 法二: [fedor ...

  5. Eclipse中直接双击执行bat时路径问题

    之前bat中使用的是 cd %cd% 这样在文件夹中直接运行bat是没问题的 但在eclipse中运行, 取得的路径就是eclipse.exe的所在路径 而如果需要获得bat文件的实际所在路径 应该使 ...

  6. [LeetCode]题解(python):091 Decode Ways

    题目来源 https://leetcode.com/problems/decode-ways/ A message containing letters from A-Z is being encod ...

  7. Mockups

    Balsamiq Mockups 是一款免费的手绘风格的产品原型设计软件,它一经推出就广受好评,它比纸质的产品原型设计图更加方便存储,而且是简约清爽的手绘风格,UI控件支持自动拖拽,并且可以实现自动对 ...

  8. [转]Android 延迟执行

    开启新线程 new Thread(new Runnable(){ public void run(){ Thread.sleep(XXXX); handler.sendMessage(); //告诉主 ...

  9. sell-- wordPOI

    1. http://poi.apache.org/ 2.创建项目,结构如下 三: 查看效果 打开: 测试源码: /* ========================================= ...

  10. 我的工具箱之MyEclipse9.1

    下载地址:http://pan.baidu.com/s/1bbuN1s 这个工具是用来开发Java程序,自带JDK和Tomcat,功能全面周到,使用方便. 市面上MyEclipse版本很多,但都需要破 ...