Leetcode 75 Sort Colors

2018-01-12 15:00:51 浏览数 (1)

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,所以可以直接统计出现次数,最后直接塞进去就行了

代码语言:javascript复制
class Solution {
public:
    void sortColors(vector<int>& nums) {
        int a[3]={0};
        for(int i=0;i<nums.size();i  ) a[nums[i]]  ;
        nums.clear();
        for(int i=0;i<3;i  )
            for(int j=0;j<a[i];j  ) 
                nums.push_back(i);
    }
};

0 人点赞