【Leetcode】621.任务调度器C++(用map解决—虚拟队列法)

在这里插入图片描述在这里插入图片描述


#include "iostream"

#include "vector"

#include "unordered_map"

using namespace std;

// a a a b b b
class Solution
{
public:
    int leastInterval(vector<char> &tasks, int n)
    {
        int size = tasks.size();
        if (n == 0)
        {
            return size;
        }
        unordered_map<char, int> m;
        for (char c : tasks)
        {
            if (m.count(c))
            {
                m[c]++;
            }
            else
            {
                m[c] = 1;
            }
        }
        unordered_map<char, int>::iterator iter;
        int max = 0;
        for (iter = m.begin(); iter != m.end(); iter++)
        {
            if (max < m[iter->first])
            {
                max = m[iter->first];
            }
        }
        if(size>max*(n+1))
        {
            return size;
        }
        int ans = (max - 1) * (n + 1);
        for (iter = m.begin(); iter != m.end(); iter++)
        {
            if (m[iter->first] == max)
            {
                ans += 1;
            }
        }
        return ans;
    }
};

int main(int argc, char const *argv[])
{
    int n;
    cin >> n;

    vector<char> tasks;

    char x;

    while (true)
    {
        cin >> x;
        tasks.push_back(x);
        if (cin.get() == '\n')
            break;
    }

    Solution so;
    cout << so.leastInterval(tasks, n) << endl;

    return 0;
}
发布了103 篇原创文章 · 获赞 128 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_44936889/article/details/104103636
今日推荐