Every day a Leetcode
题目来源:2462. 雇佣 K 位工人的总代价
解法1:小根堆
雇佣过程可以用两个最小堆来模拟,一个负责维护 costs 剩余数字的最前面 candidates 个数的最小值,另一个负责维护 costs 剩余数字的最后面 candidates 个数的最小值。
具体算法如下:
- 设 cost 的长度为 n。如果 2*candidates+k>n,我们一定可以选到 cost 中最小的 k 个数,所以直接将 cost 从小到大排序,返回 cost 的前 k 个数之和。
- 初始化答案 ans=0。初始化最小堆 pre 为 costs 最前面的 candidates 个数,初始化最小堆 suf 为 costs 最后面的 candidates 个数。初始化下标 i=candidates,j=n−1−candidates。
- 循环 k 次。每次循环,如果 pre 的堆顶小于等于 suf 的堆顶,则弹出 pre 的堆顶,加入答案,然后把 costs[i] 加入 pre,i 自增 1;否则,弹出 suf 的堆顶,加入答案,然后把 costs[j] 加入 suf,j 自减 1。
- 返回答案。
代码:
/*
* @lc app=leetcode.cn id=2462 lang=cpp
*
* [2462] 雇佣 K 位工人的总代价
*/
// @lc code=start
class Solution
{
public:
long long totalCost(vector<int> &costs, int k, int candidates)
{
int n = costs.size();
if (2 * candidates + k > n)
{
ranges::sort(costs);
return accumulate(costs.begin(), costs.begin() + k, 0LL);
}
priority_queue<int, vector<int>, greater<>> pre, suf;
for (int i = 0; i < candidates; i++)
{
pre.push(costs[i]);
suf.push(costs[n - 1 - i]);
}
long long ans = 0LL;
int i = candidates, j = n - 1 - candidates;
while (k--)
{
// 如果有多位代价相同且最小的工人,选择下标更小的一位工人
if (pre.top() <= suf.top())
{
ans += pre.top();
pre.pop();
pre.push(costs[i]);
i++;
}
else
{
ans += suf.top();
suf.pop();
suf.push(costs[j]);
j--;
}
}
return ans;
}
};
// @lc code=end
结果:
复杂度分析:
时间复杂度:O((c+k)log(c+k)),其中 c 是数组 candidate 的元素个数。
空间复杂度:O(c),其中 c 是数组 candidate 的元素个数。