Sort Colors
2016-07-20 21:15
441 查看
题目描述:
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.
解题思路:
类似于快排中partition过程。不过要用三个指针,一前begin,一中current,一后end,
begin与current都初始化指向数组首部,end初始化指向数组尾部。
(1)current遍历整个数组序列,current指1时,不交换,current++;
(2)current指0时,与begin交换,而后current++,begin++;
(3)current指2时,与end交换,而后current不变,end--。<
4000
br />
AC代码如下:
class Solution {
public:
void sortColors(vector<int>& nums) {
if (nums.size() == 0) return;
int begin = 0, current = 0, end = nums.size() - 1;
while (current <= end){
if (nums[current] == 0){
swap(nums[begin], nums[current]);
++begin;
++current;
}
else if (nums[current] == 1){
++current;
}
else{//nums[middle]=2
swap(nums[current], nums[end]);
--end;
}
}
}
};
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.
解题思路:
类似于快排中partition过程。不过要用三个指针,一前begin,一中current,一后end,
begin与current都初始化指向数组首部,end初始化指向数组尾部。
(1)current遍历整个数组序列,current指1时,不交换,current++;
(2)current指0时,与begin交换,而后current++,begin++;
(3)current指2时,与end交换,而后current不变,end--。<
4000
br />
AC代码如下:
class Solution {
public:
void sortColors(vector<int>& nums) {
if (nums.size() == 0) return;
int begin = 0, current = 0, end = nums.size() - 1;
while (current <= end){
if (nums[current] == 0){
swap(nums[begin], nums[current]);
++begin;
++current;
}
else if (nums[current] == 1){
++current;
}
else{//nums[middle]=2
swap(nums[current], nums[end]);
--end;
}
}
}
};
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- C++联合体转换成C#结构的实现方法
- C++高级程序员成长之路
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题
- C++变位词问题分析
- C/C++数据对齐详细解析
- C++基于栈实现铁轨问题
- C++中引用的使用总结
- 使用Lua来扩展C++程序的方法
- C++中调用Lua函数实例
- Lua和C++的通信流程代码实例
- C++的template模板中class与typename关键字的区别分析
- C与C++之间相互调用实例方法讲解