leetcode 976. Largest Perimeter Triangle (python)

199 阅读1分钟

描述

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 降序排序,然后从头开始每三个边判断一次是否是合法三角形,如果合法则是最长的长度直接返回即可。如果不合法则继续对之后的三个边进行判断,以此类推,如果遍历完仍没有合法的最大长度,则返回 0 。

解答

class Solution(object):
    def largestPerimeter(self, A):
        """
        :type A: List[int]
        :rtype: int
        """
        A = sorted(A,reverse=True)
        for i in range(2,len(A)):
            if A[i-2]< A[i-1]+A[i]:
                return A[i-2]+A[i-1]+A[i]
        return 0
    	
        
        	      
		

运行结果

Runtime: 144 ms, faster than 100.00% of Python online submissions for Largest Perimeter Triangle.
Memory Usage: 14.8 MB, less than 59.40% of Python online submissions for Largest Perimeter Triangle.

原题链接:leetcode.com/problems/la…

您的支持是我最大的动力