版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_24133491/article/details/89011374
Description:
Given an array A of positive lengths, return the largest perimeter of a triangle with non-zero area, formed from 3 of these lengths.
If it is impossible to form any triangle of non-zero area, return 0.
Example 1:
Input: [2,1,2]
Output: 5
Example 2:
Input: [1,2,1]
Output: 0
Example 3:
Input: [3,2,3,4]
Output: 10
Example 4:
Input: [3,6,2,3]
Output: 8
Note:
- 3 <= A.length <= 10000
- 1 <= A[i] <= 10^6
题意:给定一个数组A,每个元素表示边的长度,现在要求计算这些边可组成的三角形的最大周长,如果不存在任何三角形则返回0;
解法:要组成最大周长的三角形自然先检查最大的那些边,所以我们第一步首先对这个数组A进行排序后,从最大的边开始寻找满足条件的三条边,(假设为 ,且 )即
- 任意两边之和大于第三边,有序情况下,只需满足 即可
- 任意两边之差小于第三边,有序情况下,只需满足 即可
Java
class Solution {
public int largestPerimeter(int[] A) {
int res = 0;
Arrays.sort(A);
int max = A.length - 1;
for (int i = A.length - 3; i != -1; i--) {
if (A[i] + A[i + 1] > A[max] && A[max] - A[i] < A[i + 1]) {
res = A[i] + A[i + 1] + A[max];
break;
} else if (A[i] + A[i + 1] <= A[max]) {
max--;
}
}
return res;
}
}