leetcode_75. Sort Colors题解

来源:互联网 发布:淘宝店铺音乐要钱吗 编辑:程序博客网 时间:2024/06/07 07:31

题目链接
【题目】
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.
这里写图片描述


【分析】
将数组中的数按颜色排序,其实就是按0,1,2排序


解法1:
用count计算0,1,2的个数,然后从0到2开始往后排

class Solution {public:    void sortColors(vector<int>& nums) {        int count[3] = {0};        for( int i = 0 ; i < nums.size() ; i ++ ){            count[nums[i]] ++;        }        for( int i = 0 , index = 0 ; i < 3 ; i ++ ){            for( int j = 0 ; j < count[i] ; j ++ )  nums[index++] = i;        }    }};

解法2:

class Solution {public:    void sortColors(vector<int>& nums) {        int red = 0 ; int blue = nums.size() - 1;        for( int i = 0 ; i < blue + 1 ; ){            if( nums[i] == 0 ) swap( nums[i++] , nums[red++] );            else if( nums[i] == 2 ) swap( nums[i] , nums[blue--] );            else i++;        }    }};
0 0