gpt4 book ai didi

java - 使用 lambda 表达式按降序对二维数组进行排序

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:56:38 24 4
gpt4 key购买 nike

我正在处理一些面试问题并遇到了这个问题。除了下一行的内容,我完全理解代码:

Arrays.sort(pair, (a, b) -> (b[0] - a[0]));

给定N名运动员的成绩,求出他们的相对名次和得分最高的前三名,分别授予奖牌:“金牌”、“银牌”、“铜牌” .

Example 1: Input: [5, 4, 3, 2, 1] Output: ["Gold Medal", "Silver Medal", "Bronze Medal", "4", "5"] Explanation: The first three athletes got the top three highest scores, so they got "Gold Medal", "Silver Medal" and "Bronze Medal". For the left two athletes, you just need to output their relative ranks according to their scores.

 public class Solution {

public String[] findRelativeRanks(int[] nums) {

int[][] pair = new int[nums.length][2];

for (int i = 0; i < nums.length; i++) {
pair[i][0] = nums[i];
pair[i][1] = i;
}

Arrays.sort(pair, (a, b) -> (b[0] - a[0]));

String[] result = new String[nums.length];

for (int i = 0; i < nums.length; i++) {
if (i == 0) {
result[pair[i][1]] = "Gold Medal";
}
else if (i == 1) {
result[pair[i][1]] = "Silver Medal";
}
else if (i == 2) {
result[pair[i][1]] = "Bronze Medal";
}
else {
result[pair[i][1]] = (i + 1) + "";
}
}

return result;
}
}

最佳答案

这是调用 Arrays.sort 方法,使用用 lambda 表达式定义的 Comparator 对数组 pair 进行排序。只要类型推断可以确定我们需要一个只需要定义一个函数的类的对象,就可以使用 lambda 表达式。

参见 http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/Lambda-QuickStart/index.html#section2有关语法的更多信息。

在幕后,该函数将针对数组中的成对元素调用多次,并将根据比较函数从“最小”到“最大”排序。如果函数返回负数,则 a 将被视为“大于”b,如果返回正数,则 a 为“小于 b,如果 0 则为平局。

这里的技巧是比较函数返回 b[0] - a[0] ,这与通常的方向相反。因此,它将按从大到小的顺序排序。最大的当然是金牌得主。其次是银牌,然后是铜牌。

关于java - 使用 lambda 表达式按降序对二维数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42125658/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com