Skip to content

Latest commit

 

History

History
112 lines (50 loc) · 1.52 KB

0976._Largest_Perimeter_Triangle.md

File metadata and controls

112 lines (50 loc) · 1.52 KB

976. Largest Perimeter Triangle

难度: Easy

刷题内容

原题连接

内容描述

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

解题方案

思路 1 - 时间复杂度: O(N)- 空间复杂度: O(1)******

首先设三角形三边为a, b, c

那么肯定满足三个条件

  1. a + b > c
  2. a + c > b
  3. b + c > a

如果我们固定让c最大的话,那么只需要继续确认条件1即可

那么我们可以先排序A,我们当然希望c越大越好,所以逆序遍历即可

另外如果大小最接近c的a和b都无法满足条件1的话, 其他的a和b也不需要考虑了,例如A = [1,2,2,3,5],此时c为5,如果连a = 2,b = 3都无法满足条件1的话, 试问a和b变得更小了是不是更不可能满足条件1了?

class Solution:
    def largestPerimeter(self, A):
        """
        :type A: List[int]
        :rtype: int
        """
        A.sort() 
        for i in range(len(A)-1, 1, -1):
            if A[i-1] + A[i-2] > A[i]:
                return A[i-1] + A[i-2] + A[i]
        return 0