牛牛与三角形 Java
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
* 返回在所有合法的三角形的组成中,最大的三角形的周长减去最小的三角形的周长的值
* @param n int整型 代表题目中的n
* @param a int整型一维数组 代表n个数的大小
* @return int整型
*/
public int solve (int n, int[] a) {
// write code here
Arrays.sort(a);
int max = 0, min = Integer.MAX_VALUE;
for (int i = n-1; i > 1; i--) {
if (a[i-1]+a[i-2] > a[i]) {
max = a[i] + a[i-1] + a[i-2];
break;
}
}
TreeSet<Integer> set = new TreeSet<>();
set.add(a[0]);
for (int j = 2; j < n; j++) {
int temp = a[j] - a[j-1];
Integer num = set.higher(temp);
if (num != null) {
min = Math.min(min, a[j]+a[j-1]+num);
}
set.add(a[j-1]);
}
return max-min;
}
}比赛的时候wa了,结果是测试的问题

京公网安备 11010502036488号