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.

2. 思路

对0、1、2进行计数后再填充。

3. 代码

class Solution {
public:

// 好无聊:直接对0、1、2进行计数,然后填充
void sortColors(vector<int>& nums) {
    int cnt[3] = {0, 0, 0};
    for (int i = 0; i < nums.size(); i++) {
        cnt[nums[i]]++;
    }
    cnt[1] += cnt[0];
    for (int i = 0; i < nums.size(); i++) {
        if (i < cnt[0]) {
            nums[i] = 0;
        } else if (i < cnt[1]) {
            nums[i] = 1;
        } else {
            nums[i] = 2;
        }
    }
}

};


knzeus
72 声望28 粉丝

行万里路,读万卷书