LeetCode | 75. Sort Colors

来源:互联网 发布:淘宝刷到一个钻多少钱 编辑:程序博客网 时间:2024/06/06 09:11

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.

Solution

class Solution {public:    void sortColors(vector<int>& nums)    {        //桶排序        int len = nums.size();        int Count[3] = {};        for(int i=0;i<len;i++)            Count[nums[i]]++;        for(int i=0;i<Count[0];i++)            nums[i] = 0;        for(int i=Count[0];i<Count[0]+Count[1];i++)            nums[i] = 1;        for(int i=Count[0]+Count[1];i<len;i++)            nums[i] = 2;    }};