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++;        }            }};


0 0