8.24 - hard - 105

587. Erect the Fence

利用一種算法叫做Monotone Chain,加上之前的旋轉(zhuǎn)卡殼。。。還有一道求是否所有點(diǎn)形成convex hull 這三個(gè)解法好好搞一搞清楚

    def outerTrees(self, points):
        """Computes the convex hull of a set of 2D points.

        Input: an iterable sequence of (x, y) pairs representing the points.
        Output: a list of vertices of the convex hull in counter-clockwise order,
          starting from the vertex with the lexicographically smallest coordinates.
        Implements Andrew's monotone chain algorithm. O(n log n) complexity.
        """

        # Sort the points lexicographically (tuples are compared lexicographically).
        # Remove duplicates to detect the case we have just one unique point.
        # points = sorted(set(points))
        points = sorted(points, key=lambda p: (p.x, p.y))

        # Boring case: no points or a single point, possibly repeated multiple times.
        if len(points) <= 1:
            return points

        # 2D cross product of OA and OB vectors, i.e. z-component of their 3D cross product.
        # Returns a positive value, if OAB makes a counter-clockwise turn,
        # negative for clockwise turn, and zero if the points are collinear.
        def cross(o, a, b):
            # return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])
            return (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x)

        # Build lower hull
        lower = []
        for p in points:
            while len(lower) >= 2 and cross(lower[-2], lower[-1], p) < 0:
                lower.pop()
            lower.append(p)

        # Build upper hull
        upper = []
        for p in reversed(points):
            while len(upper) >= 2 and cross(upper[-2], upper[-1], p) < 0:
                upper.pop()
            upper.append(p)

        # Concatenation of the lower and upper hulls gives the convex hull.
        # Last point of each list is omitted because it is repeated at the
        # beginning of the other list.
        # return lower[:-1] + upper[:-1]
        return list(set(lower[:-1] + upper[:-1]))
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 連續(xù)第二年在首都劇場(chǎng)精品劇目邀請(qǐng)演出追以色列蓋謝爾劇目,大概是去年的《耶路撒冷之鴿》亮相給我們帶太多的驚喜,這次號(hào)...
    默默712100閱讀 449評(píng)論 0 2
  • 最近幾日連續(xù)有不下十個(gè)小伙伴或當(dāng)面、或私信、或留言的傾訴一個(gè)在我看來(lái)極其嚴(yán)重的問(wèn)題:不自信! 是的,很嚴(yán)重,雖然他...
    塵世知行者閱讀 620評(píng)論 0 2
  • 天橋底下有個(gè)邋遢的老乞丐睡眼朦朧地看著車水馬龍的世人在他的腳邊竟然有一只超可愛(ài)的奶狗晶亮亮的黑眼珠精神地看著這世界...
    艾黑丫閱讀 380評(píng)論 31 37

友情鏈接更多精彩內(nèi)容