75. Sort Colors 荷兰国旗问题

Given an array with n objects colored red, white or blue, sort them in-place 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.

Example:

Input: [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]
class Solution {
public:
    void sortColors(vector<int>& nums) {
        int p1 = 0, p2 = 0, p3 = nums.size() - 1;
        while(p2 <= p3)
        {
            if (nums[p2] == 0)
            {
                swap(nums[p1], nums[p2]);
                ++p1;
                ++p2;
            }
            else if(nums[p2] == 2)
            {
                swap(nums[p2], nums[p3]);
                --p3;
            }
            else
            {
                ++p2;
            }
        }
    }
};

 

posted @ 2020-02-11 20:01  强威  阅读(112)  评论(0编辑  收藏  举报