Sort Colors(荷兰旗问题)

75. Sort Colors

My Submissions
Question Editorial Solution
Total Accepted: 94286  Total Submissions: 272931  Difficulty: Medium

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.

click to show follow up.

Subscribe to see which companies asked this question

Show Tags
Show Similar Problems


第一种方法:最直接的方法
(1)就是先遍历数组一遍,记录0、1、2的个数x、y、z
(2)遍历数组,依次赋值数组x个0,y个1,z个2
class Solution
{
public:
    void sortColors(vector<int>& nums)
    {
        int red = 0, white = 0, blue = 0;
        for (auto color : nums)
        {
            if (color == 0)
                ++red;
            else if (color == 1)
                ++white;
            else
                ++blue;
        }
        
        int i;
        for (i = 0; i < red; ++i)
            nums[i] = 0;
        for (; i < red + white; ++i)
            nums[i] = 1;
        for (; i < nums.size(); ++i)
            nums[i] = 2;
    }
};


第二种方法:有点快速排序的味道
(1)red 记录从头开始 0 的下一个位置
(2)blue 记录从末尾开始 2 的下一个位置
(2)从头开始遍历数组,到 blue 位置结束

class Solution
{
public:
    void sortColors(vector<int>& nums)
    {
        int red = 0, blue = nums.size() - 1;

        int i = 0; //注意条件, i <= blue ,容易写成 i < nums.size()
        while (i<= blue)
        {
            //把 0 放到对应的 red 位置后,nums[i] 的位置还有可能是 2,所以不能 ++i
            if (nums[i] == 0)
            {
                if (i == red) {
                    ++i;
                    ++red;
                }
                else {
                    Swap(nums[i], nums[red]);
                    ++red;
                }
            }
            
            //把 2 放到对应的 blue 位置后,nums[i] 的位置还有可能是 1,所以不能 ++i
            else if (nums[i] == 2)
            {
                Swap(nums[i], nums[blue]);
                --blue;
            }
            
            // 只有当 nums[i] == 1 的时候,i 往前移动
            else
            {
                ++i;
            }
        }
    }

    void Swap(int &a, int &b)
    {
        int temp = a;
        a = b;
        b = temp;
    }
};



你可能感兴趣的:(算法)