LeetCode: Sort Colors 解题报告

时间:2022-09-07 10:46:14

Sort Colors
Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue.

Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.

Note:
You are not suppose to use the library's sort function for this problem.

click to show follow up.

Follow up:
A rather straight forward solution is a two-pass algorithm using counting sort.
First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's.

Could you come up with an one-pass algorithm using only constant space?

LeetCode: Sort Colors 解题报告

Solution 1:

类似radix sort, 先扫描一次得知所有的值出现的次数,再依次setup它们即可

ref: http://blog.csdn.net/fightforyourdream/article/details/15025713

http://en.wikipedia.org/wiki/Radix_sort

Radix sort

From Wikipedia, the free encyclopedia
Radix sort
Class Sorting algorithm
Data structure Array
Worst case performance LeetCode: Sort Colors 解题报告
Worst case space complexity LeetCode: Sort Colors 解题报告

In computer science, radix sort is a non-comparative integer sorting algorithm that sorts data with integer keys by grouping keys by the individual digits which share the same significant position and value. A positional notation is required, but because integers can represent strings of characters (e.g., names or dates) and specially formatted floating point numbers, radix sort is not limited to integers. Radix sort dates back as far as 1887 to the work of Herman Hollerith on tabulating machines.[1]

 public void sortColors1(int[] A) {
if (A == null || A.length == ) {
return;
} int len = A.length; int red = ;
int white = ;
int blue = ; for (int i = ; i < len; i++) {
if (A[i] == ) {
red++;
} else if (A[i] == ) {
white++;
} else {
blue++;
}
} for (int i = ; i < len; i++) {
if (red > ) {
A[i] = ;
red--;
} else if (white > ) {
A[i] = ;
white--;
} else {
A[i] = ;
}
}
}

Solution 2:

使用双指针指向左边排好的0和右边排好的1,再加一个指针cur扫描整个数组。一趟排序下来就完成了。相当快捷。

注意:与右边交换之后,cur不能移动,因为你有可能交换过来是1或是0,还需要与左边交换。而与左边交换后,cur就可以向右边移动了。

 public void sortColors(int[] A) {
if (A == null || A.length == ) {
return;
} int len = A.length - ;
int left = ;
int right = len; int cur = ;
while (cur <= right) {
if (A[cur] == ) {
// 换到右边,换过来的有可能是0,也有可能是1,所以cur要停留 swap(A, cur, right);
right--;
} else if (A[cur] == ) {
// 从左边换过来的只可能是1,所以可以直接cur++
// 因为所有的2全部换到右边去了。 swap(A, cur, left);
left++;
cur++;
} else {
cur++;
}
}
} public void swap(int[] A, int n1, int n2) {
int tmp = A[n1];
A[n1] = A[n2];
A[n2] = tmp;
}

 December 22nd, 2014 redo

补充一个例子如下:

注:非常要注意的是,我们要使用cur <= right作为边界值。因为right 指向的是未判断的值。所以当cur == right时,此值仍然需要继续判断。

LeetCode: Sort Colors 解题报告

 public class Solution {
public void sortColors(int[] A) {
if (A == null || A.length == 0) {
return;
} int left = 0; // Bug 1: right is wrong.
int right = A.length - 1; int cur = 0; // left: the first one which is not 0
// right: the first one which is not 2
// So we should use <= because right may be not dealed with.
while (cur <= right) {
switch (A[cur]) {
case 0:
// Bug 0: Forget to add A.
swap(A, left, cur);
left++;
cur++;
break;
case 1:
cur++;
break;
case 2:
swap(A, cur, right);
right--;
// 这里不cur++的原因是,有可能从右边换过来有0,1还要继续处理
break; default:
cur++;
break;
}
}
} public void swap(int[] A, int n1, int n2) {
int tmp = A[n1];
A[n1] = A[n2];
A[n2] = tmp;
}
}

Follow up:

附上写得不错的一个博客:

http://blog.csdn.net/kenden23/article/details/17440519

以及本题的后续: Lintcode: Sort Colors II 解题报告

GitHub:

https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/sort/SortColors.java

LeetCode: Sort Colors 解题报告的更多相关文章

  1. 【LeetCode】75&period; Sort Colors 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 计数排序 双指针 日期 题目地址:https://l ...

  2. 【LeetCode】Sort Colors 解题报告

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

  3. LeetCode&colon; Sort List 解题报告

    Sort List Sort a linked list in O(n log n) time using constant space complexity. 使用Merge Sort, 空间复杂度 ...

  4. 【LeetCode】147&period; Insertion Sort List 解题报告(Python)

    [LeetCode]147. Insertion Sort List 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu 个人博客: h ...

  5. LeetCode&colon; Combination Sum 解题报告

    Combination Sum Combination Sum Total Accepted: 25850 Total Submissions: 96391 My Submissions Questi ...

  6. 【LeetCode】Permutations 解题报告

    全排列问题.经常使用的排列生成算法有序数法.字典序法.换位法(Johnson(Johnson-Trotter).轮转法以及Shift cursor cursor* (Gao & Wang)法. ...

  7. LeetCode - Course Schedule 解题报告

    以前从来没有写过解题报告,只是看到大肥羊河delta写过不少.最近想把写博客的节奏给带起来,所以就挑一个比较容易的题目练练手. 原题链接 https://leetcode.com/problems/c ...

  8. C&num;版 - LeetCode 148&period; Sort List 解题报告&lpar;归并排序小结&rpar;

    leetcode 148. Sort List 提交网址: https://leetcode.com/problems/sort-list/  Total Accepted: 68702 Total ...

  9. 【LeetCode】148&period; Sort List 解题报告(Python & C&plus;&plus;)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 日期 题目地址:https://leetcode.c ...

随机推荐

  1. MySQL主从复制实现

    上回提到了用ThinkPHP框架来实现数据库的读写分离,现在就来简单说说MySQL的主从复制. 形式 一主一从(也就是这里要实现的形式) 主主复制 一主多从 多主一从(MySQL5.7开始支持) 联级 ...

  2. 0029 Java学习笔记-面向对象-枚举类

    可以创建几个对象? n多个:大部分的类,都可以随意创建对象,只要内存不爆掉 1个:比如单例类 有限的几个:采用单例类的设计思路,可以只允许创建少数的几个特定的对象:还有就是枚举类. 创建少数几个对象, ...

  3. oracle触发器详解(转)

    触发器是许多关系数据库系统都提供的一项技术.在ORACLE系统里,触发器类似过程和函数,都有声明,执行和异常处理过程的PL/SQL块. 8.1 触发器类型 触发器在数据库里以独立的对象存储,它与存储过 ...

  4. 《C&plus;&plus; Primer 4th》读书笔记 第5章-表达式

    原创文章,转载请注明出处: http://www.cnblogs.com/DayByDay/p/3912114.html

  5. HEVC测试序列(百度云网盘分享)

    巧妇难为无米之炊,身为一个码农怎能碗里没有米呢?想必很多朋友都碰到下载测试序列的困惑,为了减少麻烦,现提供HEVC所有测试序列的下载,上传到百度云网盘上,方便大家下载.主要的测试序列如下: Test ...

  6. input框中修改placeholder的样式

    有时间input标签的placeholder属性会出现问题,下面是修改placeholder的样式demo input::-webkit-input-placeholder{ color:red; f ...

  7. IntelliJ IDEA 2018 设置代码超出限制自动换行&lpar;最新版&rpar;

    环境信息 * IntelliJ IDEA版本:ULTIMATE 2018.2.3:* 系统:Windows 10: 怎么设置IntelliJ IDEA 2018代码一行的换行宽度限制呢? 设置方法:` ...

  8. 晚期(运行期)优化---HotSpot虚拟机内的即时编译器

    最初java程序是通过解释器进行解释执行的,当虚拟机发现某个方法或代码块的运行特别频繁时,就会把这些代码认定为“热点代码”.为了提高热点代码的执行效率,在运行时,虚拟机将会把这些代码编译成与本地平台相 ...

  9. ES6 Decorator 修饰器

    目的:  修改类的一种方法,修饰器是一个函数 编译: 安装 babel-plugin-transform-decortators-legacy .babelrd      plugins: [&quo ...

  10. Groovy 与 Python 的差异【翻译】

    本文内容 General 一般 Lists 列表 Maps 映射 Ranges/Slices 范围/片段 Object access 对象访问 参考资料 Groovy 是一种基于 JVM 的敏捷开发语 ...