587.leetcode題目講解(Python):安裝柵欄(Erect the Fence)

1. 題目

2. 解題思路

這道題還是比較難,需要一些背景知識(已整理到第3節中)。本題的解題思路其實是需要尋找一個點集的凸外殼,Jarvis’s 算法比較容易理解,我們從x軸最左邊的點出發,尋找“最逆時針”的下一個點,直到回到最x軸左邊的點,完成凸外殼的構建。

3. 背景知識

3.1 凸與非凸

凸:集合中任意兩點的連線在集合中
非凸:集合中存在兩點,其連線不在集合中

3.2 三點方向(Orientation)

如圖所示,三個有序點的方向可以分爲順時針、逆時針和共線三種。

如果(ABC)是共線,那麼(CBA)也是共線,如果(ABC)是順時針,那麼(CBA)爲逆時針。

3.3 方向計算

給定三點 A(x1, y1), B (x2, y2), C(x3, y3), (ABC)方向可以通過線段斜率來計算。

線段AB的斜率 :i = (y2 - y1) / (x2 - x1)
線段BC的斜率 : j = (y3 - y2) / (x3 - x3)

i < j (左圖):逆時針
i > j  (右圖):順時針
i = j  : 共線

所以,方向 r 可以這麼計算:

r = (y2 - y1)(x3 - x2) - (y3 - y2)(x2 - x1)

r > 0, 順時針, 反之 r < 0 爲逆時針,r = 0則爲共線。

  1. 參考代碼
'''
@auther: Jedi.L
@Date: Sat, May 4, 2019 12:04
@Email: [email protected]
@Blog: www.tundrazone.com
'''


class Solution:
    def orientation(self, a, b, c):
        ori = (b[1] - a[1]) * (c[0] - b[0]) - (c[1] - b[1]) * (b[0] - a[0])
        if ori == 0:
            return 0  # colinear
        res = 1 if ori > 0 else 2  # clock or counterclock wise
        return res

    def inbetween(self, a, b, c):
        ori = (b[1] - a[1]) * (c[0] - b[0]) - (c[1] - b[1]) * (b[0] - a[0])
        if ori == 0 and min(a[0], c[0]) <= b[0] and max(
                a[0], c[0]) >= b[0] and min(a[1], c[1]) <= b[1] and max(
                    a[1], c[1]) >= b[1]:
            return True  # b in between a , c

    def outerTrees(self, points):
        points.sort(key=lambda x: x[0])
        lengh = len(points)

        # must more than 3 points
        if lengh < 4:
            return points

        hull = []
        a = 0
        start = True
        while a != 0 or start:
            start = False
            hull.append(points[a])
            c = (a + 1) % lengh
            for b in range(0, lengh):
                if self.orientation(points[a], points[b], points[c]) == 2:
                    c = b
            for b in range(0, lengh):
                if b != a and b != c and self.inbetween(
                        points[a], points[b],
                        points[c]) and points[b] not in hull:
                    hull.append(points[b])

            a = c
        return hull


如何刷題

Leetcode 題目的正確打開方式

其他題目答案

leetcode題目答案講解彙總(Python版 持續更新)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章