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
题目理解:
给定一个数组,找出这个数组中的数能够组成的,且周长最大的三角形的周长
解题思路:
将数组按照递增顺序排序,最大周长三角形一定是三个连续的数字组成的,因为如果不连续的话,一定存在周长更长的三角形。
从数组的最后往前遍历,每一次找最后的三个数字,如果较小的两个数的和大于最大的数,那么能组成三角形,返回他们的和。
如果一直无法找到,则返回0
class Solution {
public int largestPerimeter(int[] A) {
Arrays.sort(A);
int len = A.length;
int it = len - 3;
for(; it > -1; it--){
if(A[it] + A[it + 1] > A[it + 2])
return A[it] + A[it + 1] + A[it + 2];
}
return 0;
}
}