75. Sort Colors

来源:互联网 发布:php信息管理系统 编辑:程序博客网 时间:2024/05/30 04:35

题目

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.

Follow up:
A rather straight forward solution is a two-pass algorithm using counting sort.
First, iterate the array counting number of 0’s, 1’s, and 2’s, then overwrite array with total number of 0’s, then 1’s and followed by 2’s.

Could you come up with an one-pass algorithm using only constant space?

思路

本题因为数组数值比较特殊,只有三种0,1,2;那么只要遍历数组,遇到0将其插入数组头部,遇到2将其插入到数组尾部。剩下的1就处在0,2之间。

代码

class Solution {public:    void sortColors(vector<int>& nums) {        int count =0;        for(int i=0;i<nums.size()-count;i++)        {            if(nums[i]==0&&i!=0)            {                nums.erase(nums.begin()+i);                nums.insert(nums.begin(),0);            }            else if(nums[i]==2)            {                count++;                nums.erase(nums.begin()+i);                nums.insert(nums.end(),2);                i--;            }        }        return;    }};