Leetcode Sort Colors
来源:互联网 发布:百度云 域名 编辑:程序博客网 时间:2024/06/06 10:16
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.
可以先进行一次遍历,将0和非0左右分好。然后在非0部分再进行一次遍历,将1和2分好。
代码如下:
class Solution {public: void sortColors(vector<int>& nums) { int left = 0,right = nums.size()-1; while(left < right) { while(left < nums.size() && nums[left] == 0) left++; while(right >= 0 && nums[right] != 0) right--; if(left<right) { nums[left] = nums[left]^nums[right]; nums[right] = nums[left]^nums[right]; nums[left] = nums[left]^nums[right]; left++;right--; } } right = nums.size()-1; while(left < right) { while(left < nums.size() && (nums[left] == 1 || nums[left] == 0)) left++; while(right >= 0 && nums[right] != 1) right--; if( left < right) { nums[left] = nums[left]^nums[right]; nums[right] = nums[left]^nums[right]; nums[left] = nums[left]^nums[right]; left++;right--; } } }};
阅读全文
0 0
- LeetCode: Sort Colors
- LeetCode Sort Colors
- LeetCode : Sort Colors
- leetcode 77: Sort Colors
- Leetcode 75 Sort Colors
- leetcode 101: Sort Colors
- [LeetCode]Sort Colors
- [leetcode]Sort Colors
- LeetCode-Sort Colors
- [leetcode] Sort Colors
- [LeetCode] Sort Colors
- [leetCode] Sort Colors
- LeetCode - Sort Colors
- leetcode:Sort Colors
- LeetCode | Sort Colors
- 【LeetCode】Sort Colors
- Leetcode: Sort Colors
- [LeetCode] Sort Colors
- Drawable初步介绍
- java web项目(spring项目)中集成webservice ,实现对外开放接口
- npm install 报错vue --save失败
- 怎么删除以前系统的LVM分区(Ubuntu)
- Ubuntu14.04 tensorflow安装手册
- Leetcode Sort Colors
- C++编写容器列表
- JQuery和flot插件结合动态显示服务器CPU及内存状态
- 时间管理
- Scala入门到精通——第二十四节 高级类型 (三)
- 将一个集合转化为多个集合(一维集合转为二维集合)
- css3中通过设置box-pack和box-align让div里面的各种元素垂直和水平居中的方法
- 技术构思:通过2-of-2多重签名,构建实现类闪电支付
- git的使用及遇到的问题(本地代码托管到github)