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
在一堆线段中找出3条边,使之成为一个周长最大的三角形
思路:
三角形的条件:两(较短)边之和大于第三边
因为要尽量找到最大的3条边,所以先把数组排序,最大的边都放到右边
比如 [3,2,3,4],排序后变为 [2,3,3,4]
看右边的3条边,倒数第3个和倒数第2个的和如果比最后一个小,那么左边的也就不需要再看了,肯定更小,一旦满足就返回周长
public int largestPerimeter(int[] A) {
if (A.length < 3) {
return 0;
}
Arrays.sort(A);
for (int i = A.length - 1; i > 1; i--) {
if (A[i - 2] + A[i - 1] > A[i]) {
return (A[i - 2] + A[i - 1] + A[i]);
}
}
return 0;
}