【leetcode】75. Sort Colors 三颜色的数组排序后同颜色的相邻

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.this

Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.code

Note:
You are not suppose to use the library's sort function for this problem.it

2. 思路

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

3. 代码

class Solution {
public:function

// 好无聊:直接对0、一、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;
        }
    }
}

};class

相关文章
相关标签/搜索