LeetCode 题解工作台

最大三角形面积

给你一个由 X-Y 平面上的点组成的数组 points ,其中 points[i] = [x i , y i ] 。从其中取任意三个不同的点组成三角形,返回能组成的最大三角形的面积。与真实值误差在 10 -5 内的答案将会视为正确答案 。 示例 1: 输入: points = [[0,0],[0,1…

category

3

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·数学

bolt

答案摘要

给定平面上三点 $(x_1, y_1)$, $(x_2, y_2)$, $(x_3, y_3)$,其面积公式为: $$S = \frac{1}{2} \left| x_1y_2 + x_2y_3 + x_3y_1 - x_1y_3 - x_2y_1 - x_3y_2 \right|$$

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·数学 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个由 X-Y 平面上的点组成的数组 points ,其中 points[i] = [xi, yi] 。从其中取任意三个不同的点组成三角形,返回能组成的最大三角形的面积。与真实值误差在 10-5 内的答案将会视为正确答案

 

示例 1:

输入:points = [[0,0],[0,1],[1,0],[0,2],[2,0]]
输出:2.00000
解释:输入中的 5 个点如上图所示,红色的三角形面积最大。

示例 2:

输入:points = [[1,0],[0,0],[0,1]]
输出:0.50000

 

提示:

  • 3 <= points.length <= 50
  • -50 <= xi, yi <= 50
  • 给出的所有点 互不相同
lightbulb

解题思路

方法一:枚举三点面积公式

给定平面上三点 (x1,y1)(x_1, y_1), (x2,y2)(x_2, y_2), (x3,y3)(x_3, y_3),其面积公式为:

S=12x1y2+x2y3+x3y1x1y3x2y1x3y2S = \frac{1}{2} \left| x_1y_2 + x_2y_3 + x_3y_1 - x_1y_3 - x_2y_1 - x_3y_2 \right|

我们可以枚举所有的三点组合,计算面积的最大值。

时间复杂度 O(n3)O(n^3),其中 nn 是点的数量。空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
9
10
11
12
class Solution:
    def largestTriangleArea(self, points: List[List[int]]) -> float:
        ans = 0
        for x1, y1 in points:
            for x2, y2 in points:
                for x3, y3 in points:
                    u1, v1 = x2 - x1, y2 - y1
                    u2, v2 = x3 - x1, y3 - y1
                    t = abs(u1 * v2 - u2 * v1) / 2
                    ans = max(ans, t)
        return ans
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Ensure the candidate can apply the determinant formula to compute triangle areas correctly.

  • question_mark

    Look for the ability to optimize or justify the brute-force solution given the problem constraints.

  • question_mark

    Assess if the candidate handles floating-point precision well when comparing areas.

warning

常见陷阱

外企场景
  • error

    Forgetting to apply absolute value in the area formula, which can lead to incorrect negative areas.

  • error

    Not handling precision issues when comparing floating-point values, which could affect the final result.

  • error

    Incorrectly iterating through combinations of points, potentially missing some valid triangles.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    If the number of points increases significantly, consider using optimization techniques like dynamic programming or precomputed areas.

  • arrow_right_alt

    Instead of iterating through every combination, implement geometric optimization to focus only on points forming larger triangles.

  • arrow_right_alt

    For real-time performance, modify the approach to minimize redundant area calculations by using caching or memoization.

help

常见问题

外企场景

最大三角形面积题解:数组·数学 | LeetCode #812 简单