75. Sort Colors
来源:互联网 发布:英雄无敌5mac作弊 编辑:程序博客网 时间:2024/06/03 20:30
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.
一般的方法是遍历一次整个数组,分别用3个变量记录red,white,blue的个数,然后再遍历一遍赋值。但是本题要求用O(n)的时间。因此可以用以下这个方法:
这个方法基于快排的思想,将1作为中间值,前后各设一个指针begin和end。
begin最开始指向数组头,end指向数组尾,用cur对数组进行遍历。
当nums[cur]值为0的时候,它必须在最开始。因此将begin和cur交换,begin++,cur++
当 nums[cur]值为2的时候,它必须在最尾,因此将end和cur交换,end--,此处要注意的是cur现在的值还有可能需要交换,因此cur不改变。
当 nums[cur]值为1的时候,不做任何处理,cur++
其实并不太懂为什么begin和cur交换的时候不用考虑begin交换过去的值还有可能需要交换的问题……可能是和begin和cur的初值一样有关系……
class Solution {public: void sortColors(vector<int>& nums) { int begin=0,end=nums.size()-1,cur=0; while(cur<=end){ if(nums[cur]==0){ swap(nums[begin++],nums[cur++]); } else if(nums[cur]==2){ swap(nums[end--],nums[cur]); } else cur++; } }};
- 【sort专题】75. Sort Colors
- 75. Sort Colors
- [LeetCode]75.Sort Colors
- LeetCode --- 75. Sort Colors
- [Leetcode] 75. Sort Colors
- [leetcode] 75.Sort Colors
- 75. Sort Colors
- 【leetcode】75. Sort Colors
- 75. Sort Colors
- [leetcode] 75. Sort Colors
- Leetcode 75. Sort Colors
- *LeetCode 75. Sort Colors
- 75. Sort Colors LeetCode
- 75. Sort Colors
- Leetcode 75. Sort Colors
- 75. Sort Colors
- [LeetCode]75. Sort Colors
- 75. Sort Colors
- PowerDesigner 反向生成
- Entity Framework 6 Code First系列3: 实体类M:N配置
- Linux下编译APM工具要求
- 查看APK的签名信息
- IOS开发之按虚拟键盘的return健隐藏键盘
- 75. Sort Colors
- 项目总结(2016.5-2016-11)
- 高效率开发的Android Studio插件收集
- 微信开发中遇到的问题
- Label 文字显示一行半,或者多行半
- 1508-张晨曦总结《2016年-11月-27日》【连续37天总结】
- 关于viewport的移动页面适配
- 迷宫算法全部解(搜索算法与剪枝思考)
- 混合开发(Hybrid App)之 Ionic【一】-- 认识Ionic,搭建开发环境,创建项目