75. Sort Colors

来源:互联网 发布:时代创联的网络商学院 编辑:程序博客网 时间:2024/06/05 02:18

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) {        if(nums.size() == 0) return;         int left = 0, right = nums.size()-1;         int i = 0;         while(i <= right)         {             if(nums[i] == 1)             {                 i++;             }             else if (nums[i] == 0)             {                 swap(nums[i++],nums[left++]);             }             else              {                 swap(nums[i],nums[right--]);             }         }         return;    }};
0 0
原创粉丝点击