leetCode(30):Sort Colors 分类: leetCode 2015-07-03 07:58 159人阅读 评论(0) 收藏
2015-07-03 07:58
621 查看
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.
Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
void sortColors(vector<int>& nums) {//排序时间复杂度O(n) int length=nums.size(); int zero=0; int two=length-1; while(zero<length && nums[zero]==0) {//找到第一个不为0的数的下标 zero++; } while(two>=zero && nums[two]==2) {//找到倒数第一个不为2的数的下标,zero前的数都是0 two--; } for(int i=zero;i<=two;++i) { if(nums[i]==0) {//如果为0,和zero指向的数交换,zero前移 nums[i]=1;//zero指向的值肯定是1,首先不可能为0,其次,i遍历过的地方,2都已经换到最后 nums[zero]=0; zero++; } else if(nums[i]==1) {//如果为1,则跳过 continue; } else {//如果为2,则和two指向的数交换,并更新two的值, //和zero不同,two前面的数可能还未排序 nums[i]=nums[two]; nums[two]=2; two--; while(two>=i && nums[two]==2) { two--; } i--;//先向后退一步,因为two指向的数还未进行排序 } } }
相关文章推荐
- ORACLE锁
- Oracle临时表
- leetCode(29):Happy Number
- 解析Visual Studio 2015促进生产力的10个新功能
- leetCode(29):Happy Number 分类: leetCode 2015-07-03 07:55 141人阅读 评论(0) 收藏
- 在一个按行列递增的二维数组中查找一个数是否存在
- 使用SpringAop 验证方法参数是否合法
- LeetCode #2 Add Two Numbers
- C++ 与 CDC相关的知识,点滴总结
- LeetCode #1 Two Sum
- 我们都希望在最好的年华遇见一个人,可往往是遇见一个人才迎来最最好的年华
- 【剑指Offer学习】【面试题31:连续子数组的最大和】
- 基础学习总结(八)--Intent中显示意图和隐式意图的用法
- 黑马程序员——C语言基础学习(四)---数组和指针的总结学习
- Android快速开发之appBase——实战《购物车》
- 创业中的眼界——北漂18年(15)
- 黑马程序员----OC学习笔记之category,extension,protocol
- ndk eclipse集成
- 猜猜看游戏模版
- 猜猜看显示三个图片