算法提高之LeetCode刷题

976. Largest Perimeter Triangle

2019-01-18  本文已影响1人  kross

题目

链接: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;
}
上一篇 下一篇

猜你喜欢

热点阅读