Given an array with n objects colored red, white or blue, sort them in-place 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.

Example:

Input: [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]

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 a one-pass algorithm using only constant space?
 

这道题的本质还是一道排序的题,题目中给出提示说可以用计数排序,需要遍历数组两遍,那么先来看这种方法,因为数组中只有三个不同的元素,所以实现起来很容易。

- 首先遍历一遍原数组,分别记录 0,1,2 的个数。
- 然后更新原数组,按个数分别赋上 0,1,2。

解法一:

class Solution {
public:
void sortColors(vector<int>& nums) {
vector<int> colors();
for (int num : nums) ++colors[num];
for (int i = , cur = ; i < ; ++i) {
for (int j = ; j < colors[i]; ++j) {
nums[cur++] = i;
}
}
}
};

题目中还要让只遍历一次数组来求解,那么就需要用双指针来做,分别从原数组的首尾往中心移动。

- 定义 red 指针指向开头位置,blue 指针指向末尾位置。

- 从头开始遍历原数组,如果遇到0,则交换该值和 red 指针指向的值,并将 red 指针后移一位。若遇到2,则交换该值和 blue 指针指向的值,并将 blue 指针前移一位。若遇到1,则继续遍历。

解法二:

class Solution {
public:
void sortColors(vector<int>& nums) {
int red = , blue = (int)nums.size() - ;
for (int i = ; i <= blue; ++i) {
if (nums[i] == ) {
swap(nums[i], nums[red++]);
} else if (nums[i] == ) {
swap(nums[i--], nums[blue--]);
}
}
}
};

当然我们也可以使用 while 循环的方式来写,那么就需要一个变量 cur 来记录当前遍历到的位置,参见代码如下:

解法三:

class Solution {
public:
void sortColors(vector<int>& nums) {
int left = , right = (int)nums.size() - , cur = ;
while (cur <= right) {
if (nums[cur] == ) {
swap(nums[cur++], nums[left++]);
} else if (nums[cur] == ) {
swap(nums[cur], nums[right--]);
} else {
++cur;
}
}
}
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/75

类似题目:

Sort List

Wiggle Sort II

Wiggle Sort

参考资料:

https://leetcode.com/problems/sort-colors/

https://leetcode.com/problems/sort-colors/discuss/26500/Four-different-solutions

https://leetcode.com/problems/sort-colors/discuss/26472/Share-my-at-most-two-pass-constant-space-10-line-solution

https://leetcode.com/problems/sort-colors/discuss/26760/C%2B%2B-solution-in-8-lines%3A-an-instance-of-the-Dutch-national-flag-problem-by-Edsger-Dijkstra

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] Sort Colors 颜色排序的更多相关文章

  1. 75. Sort Colors(颜色排序) from LeetCode

      75. Sort Colors   给定一个具有红色,白色或蓝色的n个对象的数组,将它们就地 排序,使相同颜色的对象相邻,颜色顺序为红色,白色和蓝色. 这里,我们将使用整数0,1和2分别表示红色, ...

  2. [LeetCode] 75. Sort Colors 颜色排序

    Given an array with n objects colored red, white or blue, sort them in-place so that objects of the ...

  3. leetCode 75.Sort Colors (颜色排序) 解题思路和方法

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

  4. [LeetCode] Sort List 链表排序

    Sort a linked list in O(n log n) time using constant space complexity. 常见排序方法有很多,插入排序,选择排序,堆排序,快速排序, ...

  5. LeetCode: Sort Colors 解题报告

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

  6. LeetCode 75. Sort Colors(排序颜色)

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

  7. LeetCode OJ:Sort Colors(排序颜色)

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

  8. [LeetCode] Sort Colors 只有3个类型的排序

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

  9. [LeetCode] Sort Colors 对于元素取值有限的数组,只遍历一遍的排序方法

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

随机推荐

  1. 用SignalR 2.0开发客服系统[系列4:负载均衡的情况下使用SignalR]

    前言 交流群:195866844 目录: 用SignalR 2.0开发客服系统[系列1:实现群发通讯] 用SignalR 2.0开发客服系统[系列2:实现聊天室] 用SignalR 2.0开发客服系统 ...

  2. 代码的坏味道(12)——平行继承体系(Parallel Inheritance Hierarchies)

    坏味道--平行继承体系(Parallel Inheritance Hierarchies) 平行继承体系(Parallel Inheritance Hierarchies) 其实是 霰弹式修改(Sho ...

  3. 【转载】C#怎么判断字符是不是汉字

    支持并尊重原创!原文地址:http://jingyan.baidu.com/article/2c8c281deb79ed0008252af1.html 判断一个字符是不是汉字通常有三种方法,第1种用 ...

  4. GridView中显示时间日期格式问题

    以下都是GridView基本常用的日期,时间格式 形式 语法 结果 注释 数字 {0:N2} 12.36   数字 {0:N0} 13   货币 {0:c2} $12.36   货币 {0:c4} $ ...

  5. Navisworks Api Quantification

    Quantification  国外有的叫定量  我们国内一些施工方叫工程量. 通过TakeOff API的开发者有机会获得更多的数据和数据可通过图形用户界面. 1 添加Navisworks的Api ...

  6. Jedis的使用

    Redis是常用的key-value存储服务器,Java使用Redis有很多方法,其中官方推荐的是Jedis. 使用Jedis,首先是下载jedis-x.x.x.jar文件并导入工程,然后运行Redi ...

  7. perl 如何匹配ASCII码以及ASCII码转换

    匹配ASCII码:   /[:ascii:]/ ASCII码转换为数字: ord() 数字转换为ASCII码: chr()

  8. xcode中的.h和.m文件分别是什么意思?各有什么用?

    .h 表示头文件,用来声明各种成员变量,方法,属性之类的.在import的时候用头文件. .m 主要用来实现.h 里声明的方法.举个例子,如果要写一个方法,你要在.h里先声明: - (void)myM ...

  9. Android Weekly Notes Issue #221

    Android Weekly Issue #221 September 4th, 2016 Android Weekly Issue #221 ARTICLES & TUTORIALS And ...

  10. iOS多线程之8.NSOPeration的其他用法

      本文主要对NSOPeration的一些重点属性和方法做出介绍,以便大家可以更好的使用NSOPeration. 1.添加依赖 - (void)addDependency:(NSOperation * ...