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

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
    原文地址: https://segmentfault.com/a/1190000007402845
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞