8.24 - hard - 105

587. Erect the Fence

利用一种算法叫做Monotone Chain,加上之前的旋转卡壳。。。还有一道求是否所有点形成convex hull 这三个解法好好搞一搞清楚

    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]))
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 连续第二年在首都剧场精品剧目邀请演出追以色列盖谢尔剧目,大概是去年的《耶路撒冷之鸽》亮相给我们带太多的惊喜,这次号...
    默默712100阅读 2,985评论 0 2
  • 最近几日连续有不下十个小伙伴或当面、或私信、或留言的倾诉一个在我看来极其严重的问题:不自信! 是的,很严重,虽然他...
    尘世知行者阅读 3,576评论 0 2
  • 天桥底下有个邋遢的老乞丐睡眼朦胧地看着车水马龙的世人在他的脚边竟然有一只超可爱的奶狗晶亮亮的黑眼珠精神地看着这世界...
    艾黑丫阅读 2,707评论 31 37