首页 > 其他 > 详细

75. Sort Colors 荷兰国旗问题

时间:2020-02-11 20:40:36      阅读:63      评论:0      收藏:0      [点我收藏+]

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

 

75. Sort Colors 荷兰国旗问题

原文:https://www.cnblogs.com/qiang-wei/p/12296493.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!