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