ZS_2462_雇佣 K 位工人的总代价

思路#

两个小顶堆借助左右两个指针将数组元素遍历,不断比较两个小顶堆的堆顶元素,累加两者更小的价格(相等优先加左边的);

为保证candidates满足条件,先进行candidates次;

最后得出总价格;

优先队列#

优先队列的本质是数据结构中的树,Java中的Queue接口用PriorityQueue实现类实现,可创建默认的小顶堆。

具体实现:

![image-20221111164214464](ZS_2462_雇佣 K 位工人的总代价.assets/image-20221111164214464.png)

代码#

public static long totalCost(int[] costs, int k, int candidates) {
Queue<Integer> leftQueue = new PriorityQueue<>();
Queue<Integer> rightQueue = new PriorityQueue<>();
int len = costs.length;
long total = 0L;
int leftP = 0, rightP = len - 1;
for (int i = 0; i < candidates; i++) {
if (leftP <= rightP)
leftQueue.offer(costs[leftP++]);
if (leftP <= rightP)
rightQueue.offer(costs[rightP--]);
}
while (k != 0) {
int minL = leftQueue.peek() == null ? Integer.MAX_VALUE : leftQueue.peek();
int minR = rightQueue.peek() == null ? Integer.MAX_VALUE : rightQueue.peek();
if (minL <= minR) {
leftQueue.poll();
total += minL;
if (leftP <= rightP)
leftQueue.offer(costs[leftP++]);
} else {
rightQueue.poll();
total += minR;
if (leftP <= rightP)
rightQueue.offer(costs[rightP--]);
}
k--;
}
return total;
}
posted @   Pilo-pillow  阅读(24)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示
主题色彩