class Solution(object):
def largestPerimeter(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
sorted_nums = sorted(nums, reverse = True)
for i in range(len(nums)-2):
if sorted_nums[i] < sorted_nums[i+1] + sorted_nums[i+2]:
return sorted_nums[i] + sorted_nums[i+1] + sorted_nums[i+2]
return 0
思路:
(1)两边之和大于第三边。注意两边之和大于第三边和两边之差小于第三边是等价的。
(2)降序排序之后的数组(假设为abcde...)前三位一定能满足a + b>c。此时围成的三角形边长最长。若前三不满足,依次向后遍历。
记一下排序的相关内容:python list排序的两种方法详解_MeTrina的博客-CSDN博客_list排序python