[关闭]
@Yano 2019-01-13T08:12:25.000000Z 字数 684 阅读 1332

LeetCode 976 Largest Perimeter Triangle

LeetCode


题目描述

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

代码

三角形的条件:两边之和>第三边。

若要构成最大的三角形周长,只需要对数组排序,一直取出最大的三个值作为三角形的边,符合条件即可返回。

证明:若数组A为自然顺序,A[N]>=A[N-1]+A[N-2],则A[N]>=A[N-1]+A[N-3],A[N]与后面的数字更不可能构成三角形,可以直接排除。

时间复杂度:O(nlogn)
空间复杂度:O(1)

  1. public int largestPerimeter(int[] A) {
  2. Arrays.sort(A);
  3. for (int i = A.length - 1; i >= 2; i--) {
  4. if (A[i - 2] + A[i - 1] > A[i]) {
  5. return A[i - 2] + A[i - 1] + A[i];
  6. }
  7. }
  8. return 0;
  9. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注