题目考察的知识点是:
双指针,贪心。
题目解答方法的文字分析:
我们可以将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; } } }