意见箱
恒创运营部门将仔细参阅您的意见和建议,必要时将通过预留邮箱与您保持联络。感谢您的支持!
意见/建议
提交建议

[leetcode] 976. Largest Perimeter Triangle

来源:恒创科技 编辑:恒创科技编辑部
2022-08-12 17:32:30


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.


[leetcode] 976. Largest Perimeter Triangle

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 <= 100001 <= A[i] <= 10^6分析

题目的意思是:求给定数组构成的最大三角形的周长。我最开始写了三重循环暴力破解了一下,发现超时了。后面发现只需要排序然后从后往前找第一个符合三角形(两边之和大于第3边)要求的就是结果了。

代码
class Solution:
def largestPerimeter(self, A: List[int]) -> int:
A.sort()
n=len(A)
for i in range(n-3,-1,-1):
if(A[i]+A[i+1]>A[i+2]):
return A[i]+A[i+1]+A[i+2]
return 0
参考文献

​​solution​​


上一篇: 租用美国服务器:潜在的风险与应对策略。 下一篇: 内网dns使用