↓快轉到主要內容
  1. LeetCode/

LeetCode 812: Largest Triangle Area

·1 分鐘· ·
LeetCode Easy Array Math Geometry Polygons
Wei Yi Chung
作者
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
目錄

基本資料
#

難易度: easy 第一次嘗試:2022-09-07

  • 提交紀錄:Wrong Answer ×2 → Accepted

解題思路
#

點最多 50 個,三點組合約 2 萬組,直接枚舉(Math 模板三)。三角形面積用鞋帶公式(外積):|(x2 - x1)(y3 - y1) - (x3 - x1)(y2 - y1)| / 2。

我的嘗試
#

前兩版想用「外接矩形面積的一半」直接算:

  • 第一版取 y 的最大最小值時還拿成了 [0](x 座標),算出負數 -0.5。
  • 第二版改正座標,但最大的三角形不一定是外接矩形的一半:[[1, 5], [2, 0], [2, 2]] 的外接矩形一半是 2.5,三角形實際面積只有 1.0。

一週後改成枚舉三點、用鞋帶公式才 AC。

正確解法
#

class Solution:
    def largestTriangleArea(self, points: List[List[int]]) -> float:
        best = 0
        for (x1, y1), (x2, y2), (x3, y3) in combinations(points, 3):
            area = abs((x2 - x1) * (y3 - y1) - (x3 - x1) * (y2 - y1)) / 2
            best = max(best, area)
        return best

複雜度
#

時間 O(n³),空間 O(1)。

要特別避免的錯誤
#

  • 最大的三角形不一定是外接矩形的一半,要真的枚舉三個點。
  • 外積可能是負的,要取絕對值。

面試口說整理
#

點數很少,我枚舉所有三點組合,用外積算三角形面積,取最大值。時間 O(n³),n 最多 50。

相關文章

LeetCode 628: Maximum Product of Three Numbers
·1 分鐘
LeetCode Easy Array Math Sorting
LeetCode 628 解題筆記:排序後答案只有兩種可能:最大的三個相乘,或最小的兩個(負數)乘最大的一個
LeetCode 598: Range Addition II
·1 分鐘
LeetCode Easy Array Math
LeetCode 598 解題筆記:每次操作都包含左上角,被加最多次的是所有操作的交集:min(a) × min(b)
LeetCode 268: Missing Number
·1 分鐘
LeetCode Easy Array Hash-Table Math Binary-Search
LeetCode 268 解題筆記:0 到 n 的總和減掉陣列總和就是缺的那個;缺的可能是 0
LeetCode 66: Plus One
·1 分鐘
LeetCode Easy Array Math
LeetCode 66 解題筆記:從最後一位往前加一,遇到 9 變 0 繼續進位,全部都是 9 時前面補 1
LeetCode 806: Number of Lines To Write String
·1 分鐘
LeetCode Easy Array String
LeetCode 806 解題筆記:模擬寫字,加上去會超過 100 就換行;剛好 100 時還留在這一行
LeetCode 766: Toeplitz Matrix
·1 分鐘
LeetCode Easy Array Matrix
LeetCode 766 解題筆記:同一條對角線的元素都相同,等價於每一格都等於左上角那格