【leetcode】976. 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:

  1. 3 <= A.length <= 10000
  2. 1 <= A[i] <= 10^6

解题思路:三角形的边长规则有两个,一是任意两边之和大于第三边,这里其实只要判断两个较短的边的边长和是否大于最长边即可;二是任意两边之差小于第三边。

代码如下:

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

猜你喜欢

转载自www.cnblogs.com/seyjs/p/10308312.html