题解 | #最高售价的两只牛#

最高售价的两只牛

https://www.nowcoder.com/practice/8e4a09d5f63d4298a8507decf5d12490

题目考察的知识点是:

双指针,贪心

题目解答方法的文字分析:

我们可以将A牛的价格和B牛的价格两两组合,并计算每对牛的总价格。然后,我们可以使用一个优先队列(最小堆)来维护当前总价格最大的k对牛。在遍历过程中,我们使用两个指针i和j来分别指向A牛的价格数组和B牛的价格数组,不断选择当前总价格最大的牛对,并将其加入优先队列

本题解析所用的编程语言:

java语言。

完整且正确的编程代码:

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param pricesA int整型一维数组
     * @param pricesB int整型一维数组
     * @param k int整型
     * @return int整型二维数组
     */
    public int[][] kPairsWithLargestSums (int[] pricesA, int[] pricesB, int k) {
        // write code here
        PriorityQueue<Struct> queue = new PriorityQueue<>( (a, b) -> {
            if (a.sum == b.sum) return pricesA[b.a] - pricesA[a.a];
            return b.sum - a.sum;
        });

        int indexA = pricesA.length;
        int indexB = pricesB.length;
        for (int i = 0; i < indexA; i++) {
            queue.add(new Struct(i, indexB - 1, 
            pricesA[i] + pricesB[indexB - 1]));
        }
        ArrayList<int[]> arr = new ArrayList<>();
        while (k-- > 0 && !queue.isEmpty()) {
            Struct res = queue.poll();
            arr.add(new int[] {pricesA[res.a], pricesB[res.b]});
            if (res.b > 0) {
                res.b--;
                res.sum = pricesA[res.a] + pricesB[res.b];
                queue.add(res);
            }
        }
        return arr.toArray(new int[0][]);
    }
    static class Struct {
        int a, b, sum;
        Struct(int a, int b, int sum) {
            this.a = a;
            this.b = b;
            this.sum = sum;
        }
    }
}

#题解#
全部评论

相关推荐

06-25 16:00
武汉大学 Java
工科研究生底薪工资就开3k啊??
机械打工仔:写文章提成的岗位工资低,你怪工科?
点赞 评论 收藏
分享
06-26 18:30
门头沟学院 Java
据说名字越长别人越关注你的昵称我觉得我要被关注了:你问问这里面有多少是正经候选人,而不是乱打招呼的
点赞 评论 收藏
分享
让资本家给我当牛做马:26的秋招还没开始啊?你找的是实习?实习的话你马上就研三了为什么还要实习?
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务