• 【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
  • 相关阅读:
    第六章学习小结
    malloc iOS
    iOS事件传递机制
    对 runloop 的理解
    深恶痛绝重写setter和getter
    数据库常见问题总结
    iOS多应用自动打包
    一段文字中包含多种语言时行间距问题
    一个成熟应用的排版方案
    Flask纪要
  • 原文地址:https://www.cnblogs.com/seyjs/p/10308312.html
Copyright © 2020-2023  润新知