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
Map<int[], Integer> map = new HashMap<>();
for (int i = 0; i < pricesA.length; i++) {
for (int j = 0; j < pricesB.length; j++) {
map.put(new int[] {pricesA[i], pricesB[j]}, pricesA[i] + pricesB[j]);
}
}
List<Map.Entry<int[], Integer>> list = new ArrayList<>(map.entrySet());
list.sort(new Comparator<Map.Entry<int[], Integer>>() {
@Override
public int compare(Map.Entry<int[], Integer> o1, Map.Entry<int[], Integer> o2) {
if (o1.getValue() > o2.getValue()) {
return -1;
} else if (o1.getValue().equals(o2.getValue())) {
return o2.getKey()[0] - o1.getKey()[0];
} else {
return 1;
}
}
});
int[][] arr = new int[k][2];
for (int i = 0; i < arr.length; i++) {
arr[i] = list.get(i).getKey();
}
return arr;
}
}
本题考察的知识点是排序,所用编程语言是java.
对于这题我将所有的排序组合和相应的售价总和存储在哈希表中,然后进行排序,输出前k对组合就是题目答案了

京公网安备 11010502036488号