976. Largest Perimeter Triangle

题目

连接:https://leetcode.com/problems...java

Given an array A of positive lengths, return the largest perimeter of a triangle with non-zero area, formed from 3 of these lengths.code

If it is impossible to form any triangle of non-zero area, return 0.orm

Example 1:排序

Input: [2,1,2]
Output: 5

Example 2:leetcode

Input: [1,2,1]
Output: 0

Example 3:get

Input: [3,2,3,4]
Output: 10

Example 4:it

Input: [3,6,2,3]
Output: 8

Note:
3 <= A.length <= 10000
1 <= A[i] <= 10^6form

思路

一个面积不为空的三角形,那么必需要最小的两条边之和大于第三边,才能构成一个三角形。而且要周长最大。很容易想到,先对数据进行排序,从最大的开始进行筛选,像窗口同样,往左侧移动,一旦找到符合条件的三角形,就是面积最大的。class

public int largestPerimeter(int[] A) {
    Arrays.sort(A);
    for (int i = A.length - 3; i >= 0; i--) {
        if (A[i] + A[i + 1] > A[i + 2]) {
            return A[i] + A[i + 1] + A[i + 2];
        }
    }
    return 0;
}
相关文章
相关标签/搜索