算法29-----最大三角形面积和周长

1、题目:最大三角形面积

给定包含多个点的集合,从其中取三个点组成三角形,返回能组成的最大三角形的面积。

示例:
输入: points = [[0,0],[0,1],[1,0],[0,2],[2,0]]
输出: 2
解释: 
这五个点如下图所示。组成的橙色三角形是最大的,面积为2。

注意:

  • 3 <= points.length <= 50.
  • 不存在重复的点。
  •  -50 <= points[i][j] <= 50.
  • 结果误差值在 10^-6 以内都认为是正确答案。

2、思路:

https://blog.csdn.net/zhangzhetaojj/article/details/80724866

三、代码:

    def largestTriangleArea(self, points):
        """
        :type points: List[List[int]]
        :rtype: float
        """
        maxres = 0

        for a in points:
            for b in points:
                for c in points:
                    newarea = 0.5* abs(a[0]*b[1] + b[0]*c[1] + c[0]*a[1] - a[0]*c[1] - b[0]*a[1] - c[0]*b[1])
                    maxres = max(maxres , newarea)
        return maxres

 

采用迭代器的集合来求解:

    def largestTriangleArea(self, points):
        """
        :type points: List[List[int]]
        :rtype: float
        """
        '''
        maxres = 0

        for a in points:
            for b in points:
                for c in points:
                    newarea = 0.5* abs(a[0]*b[1] + b[0]*c[1] + c[0]*a[1] - a[0]*c[1] - b[0]*a[1] - c[0]*b[1])
                    maxres = max(maxres , newarea)
        return maxres
        '''
        def area(a,b,c):
            newarea = 0.5* abs(a[0]*b[1] + b[0]*c[1] + c[0]*a[1] - a[0]*c[1] - b[0]*a[1] - c[0]*b[1])
            return newarea
        maxres = 0
        subSet = list(combinations(points,3))
        for i in range(len(subSet)):
            maxres = max(maxres,area(subSet[i][0],subSet[i][1],subSet[i][2]))
        return maxres

 

二、题目:最大三角形周长

给定由一些正数(代表长度)组成的数组 A,返回由其中三个长度组成的、面积不为零的三角形的最大周长。

如果不能形成任何面积不为零的三角形,返回 0

 

示例 1:

输入:[2,1,2]
输出:5

示例 2:

输入:[1,2,1]
输出:0

示例 3:

输入:[3,2,3,4]
输出:10

示例 4:

输入:[3,6,2,3]
输出:8

 

提示:

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

 

思路:O(n)

反排序A,如果第一个A[i+2] + A[i+1] > A[i]满足,则为最大的三角形周长。

代码:

from itertools import combinations
class Solution(object):
    def largestPerimeter(self, A):
        """
        :type A: List[int]
        :rtype: int
        """
        '''
        #超出时间限制
        com = combinations(A,3)
        res = 0
        for a in com:
            if max(a) * 2 < sum(a):
                res = max(res,sum(a))
                
        return res
        '''
        sort_A = sorted(A,reverse = True)
        for i in range(len(sort_A)-2):
            if sort_A[i+2] + sort_A[i+1] > sort_A[i]:
                return (sort_A[i+2] + sort_A[i+1]+sort_A[i])
        return 0

 

posted on 2018-09-11 11:31  吱吱了了  阅读(555)  评论(0编辑  收藏  举报

导航