[LeetCode OJ]75. Sort Colors

来源:互联网 发布:北京铁路局网络通信 编辑:程序博客网 时间:2024/06/03 13:24

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.


class Solution {public:    void sortColors(vector<int>& nums) {        int p = 0;        int i = 0;        int j = nums.size()-1;                while(p<=j)        {            if(nums[p] == 0)            {                if(nums[i]!=0)                    swap(nums[i],nums[p]);                i++;                p++;            }            else if(nums[p] == 1)            {                p++;            }            else            {                swap(nums[p], nums[j]);                j--;            }        }    }};


0 0
原创粉丝点击