Sort Colors(荷兰旗问题)
来源:互联网 发布:mac os x10.10安装 编辑:程序博客网 时间:2024/05/03 03:31
75. Sort Colors
My SubmissionsTotal Accepted: 94286 Total Submissions: 272931 Difficulty: Medium
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.
Subscribe to see which companies asked this question
Show Similar Problems
第一种方法:最直接的方法
(1)就是先遍历数组一遍,记录0、1、2的个数x、y、z
(2)遍历数组,依次赋值数组x个0,y个1,z个2
class Solution{public: void sortColors(vector<int>& nums) { int red = 0, white = 0, blue = 0; for (auto color : nums) { if (color == 0) ++red; else if (color == 1) ++white; else ++blue; } int i; for (i = 0; i < red; ++i) nums[i] = 0; for (; i < red + white; ++i) nums[i] = 1; for (; i < nums.size(); ++i) nums[i] = 2; }};
第二种方法:有点快速排序的味道
(1)red 记录从头开始 0 的下一个位置
(2)blue 记录从末尾开始 2 的下一个位置
(2)从头开始遍历数组,到 blue 位置结束
class Solution{public: void sortColors(vector<int>& nums) { int red = 0, blue = nums.size() - 1; int i = 0; //注意条件, i <= blue ,容易写成 i < nums.size() while (i<= blue) { //把 0 放到对应的 red 位置后,nums[i] 的位置还有可能是 2,所以不能 ++i if (nums[i] == 0) { if (i == red) { ++i; ++red; } else { Swap(nums[i], nums[red]); ++red; } } //把 2 放到对应的 blue 位置后,nums[i] 的位置还有可能是 1,所以不能 ++i else if (nums[i] == 2) { Swap(nums[i], nums[blue]); --blue; } // 只有当 nums[i] == 1 的时候,i 往前移动 else { ++i; } } } void Swap(int &a, int &b) { int temp = a; a = b; b = temp; }};
0 0
- Sort Colors(荷兰旗问题)
- LeetCode | Sort Colors(荷兰国旗问题)
- 【Sort】75. Sort Colors(计数排序、荷兰国旗问题)
- 【python】LeetCode | Sort Colors(荷兰国旗问题)
- [LeetCode] 荷兰国旗问题 Sort Colors
- 75. Sort Colors--荷兰三色国旗问题
- LeetCode(75)Sort Colors (荷兰三色旗问题 Dutch National Flag)
- 荷兰国旗问题 将3种数中重复数聚集 Sort Colors
- Sort Colors问题及解法
- Leetcode之Sort Colors 问题
- 荷兰旗问题(C语言实现)
- 荷兰旗问题
- LeetCode(75) Sort Colors
- Leetcode_c++: Sort Colors (075)
- Sort Colors
- sort colors
- Sort Colors
- Sort Colors
- 并发模式(三)——生产者-消费模式
- 69 模板(一)
- 第5周项目4长方柱类
- c# 关于继承类中构造函数的实现
- 快速排序算法 原理及golang语言实现
- Sort Colors(荷兰旗问题)
- 3.1.8 面向对象编程
- C++实验3-个人所得税计算器
- Linux大杀器命令:查找所有目录下的所有文件的字符串命令
- linux线程同步03
- UIWindow简单介绍
- Linux应用服务器搭建手册—Weblogic服务域的创建与部署
- 安卓-屏幕适配的五种方式
- JVM内幕:Java虚拟机详解