976. Largest Perimeter Triangle

題目

鏈接:https://leetcode.com/problems/largest-perimeter-triangle/

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

思路

一個面積不爲空的三角形,那麼必須要最小的兩條邊之和大於第三邊,才能構成一個三角形。並且要周長最大。很容易想到,先對數據進行排序,從最大的開始進行篩選,像窗口一樣,往左側移動,一旦找到符合條件的三角形,就是面積最大的。

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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章