75. Sort Colors
Posted 积少成多
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了75. Sort Colors相关的知识,希望对你有一定的参考价值。
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
==========
有三种颜色的物体若干,颜色分别是red,waite,blue,分别使用数组0,1,2来表示.
要求是:将这些物体按照颜色red,waite,blue排序.
=======
思路:
采用快速排序的思路:
begin:指向将要排序为red(0)的位置
end:指向将要排序为blue(2)的位置
curr:遍历指针,
如果当前元素为0,则和begin位置swap,通知begin++,curr++
如果当前元素为1,curr++
如果当前元素为2,则和end位置swap,但是curr元素不能增加,end--
====
code:
class Solution { public: void sortColors(vector<int>& nums) { int n = nums.size(); int curr,begin,end; curr = begin = 0; end = n-1; while(curr<=end){ if(nums[curr]==0){ swap(nums[begin++],nums[curr++]); }else if(nums[curr]==1){ curr++; }else if(nums[curr]==2){ swap(nums[end],nums[curr]); end--; } } } };
以上是关于75. Sort Colors的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 75. 颜色分类(Sort Colors)