976.Largest Perimeter Triangle(三角形的最大周长)

Description

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.


给定由一些正数(代表长度)组成的数组 A,返回由其中三个长度组成的、面积不为零的三角形的最大周长。

如果不能形成任何面积不为零的三角形,返回 0

题目链接:https://leetcode.com/problems/largest-perimeter-triangle/

Difficulty: easy

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

分析

  • updating(Solution)

参考代码

class Solution(object):
def largestPerimeter(self, A):
    A.sort()
    for i in xrange(len(A) - 3, -1, -1):
        if A[i] + A[i+1] > A[i+2]:
            return A[i] + A[i+1] + A[i+2]
    return 0
-------------本文结束你这么美,还坚持读完了-------------