描述
You have a list of points in the plane. Return the area of the largest triangle that can be formed by any 3 of the points.
Example:
Input: points = [[0,0],[0,1],[1,0],[0,2],[2,0]]
Output: 2
Explanation:
The five points are show in the figure below. The red triangle is the largest.
Notes:
3 <= points.length <= 50.
No points will be duplicated.
-50 <= points[i][j] <= 50.
Answers within 10^-6 of the true value will be accepted as correct.
解析
根据题意,暴力破解,遍历各个点的组合,根据公式计算面积取最大值即可,时间复杂度为 O(N^3),空间复杂度为 O(1)。
解答
class Solution(object):
def largestTriangleArea(self, points):
"""
:type points: List[List[int]]
:rtype: float
"""
def f(p1, p2, p3):
(x1, y1), (x2, y2), (x3, y3) = p1, p2, p3
return 0.5 * abs(x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2))
return max(f(a, b, c) for a, b, c in itertools.combinations(points, 3))
运行结果
Runtime: 96 ms, faster than 87.76% of Python online submissions for Largest Triangle Area.
Memory Usage: 11.8 MB, less than 65.22% of Python online submissions for Largest Triangle Area.
每日格言:生命不等于是呼吸,生命是活动。
请作者喝吃核桃 支付宝