为了找到目标分数,我们可以使用一个集合来存储不同的分数。集合会自动处理重复的分数,因此我们可以轻松地获取不同分数的数量。接下来,我们将这些分数转换为一个数组,并根据不同分数的数量来返回相应的目标分数。
以下是完善后的代码:
java
import java.util.*;
public class Main {
public static int solution(int n, int[] nums) {
// 使用 HashSet 来存储不同的分数
Set<Integer> uniqueScores = new HashSet<>();
// 将分数添加到集合中
for (int num : nums) {
uniqueScores.add(num);
}
// 将集合转换为列表并排序
List<Integer> sortedScores = new ArrayList<>(uniqueScores);
Collections.sort(sortedScores);
// 根据不同分数的数量返回目标分数
if (sortedScores.size() >= 3) {
return sortedScores.get(sortedScores.size() - 3); // 返回第三大的分数
} else {
return sortedScores.get(sortedScores.size() - 1); // 返回最大的分数
}
}
public static void main(String[] args) {
System.out.println(solution(3, new int[]{3, 2, 1}) == 1);
System.out.println(solution(2, new int[]{1, 2}) == 2);
System.out.println(solution(4, new int[]{2, 2, 3, 1}) == 1);
}
}
代码说明:
-
使用
HashSet:我们使用HashSet来存储不同的分数,这样可以自动去重。 -
转换为列表并排序:将集合转换为列表后,我们使用
Collections.sort()方法对分数进行排序。 -
判断分数数量:
- 如果不同分数的数量大于或等于 3,返回第三大的分数。
- 如果不同分数的数量小于 3,返回最大的分数。
测试用例:
在 main 方法中,我们使用了几个测试用例来验证 solution 方法的正确性。这个实现的时间复杂度是 O(n log n),主要是由于排序操作。
复制再试一次分享
(用户停止)