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;
}
相關文章
相關標籤/搜索