凸包算法-流程及代码简述

leetcode:587.安装栅栏
凸包算法:给定n个点,包围这n个点的最小面积的多边形为凸包,找到这n个点中在凸包上的点。

一、暴力法

时间复杂度:O(n^3)
空间复杂度:O(1)

算法步骤

  1. 二重循环遍历所有由两个点组成的边(总共n * (n - 1) / 2条)
  2. 如果剩余n - 2个点都在这条变的同一侧,则该条边为凸包的边,加入返回集合中。

二、方法二:Javis算法

时间复杂度:O(n^2)
空间复杂度:O(n)

算法步骤

  1. 如果元素个数小于等于3个,则全部为凸包上的点,返回全部元素
  2. 找到n个点中横坐标最小的点,将其作为初始的x点。
  3. x点的下一个点作为y点,遍历剩余的点作为z点,计算x、y、z三点的外积,外积等于0则说明xyz在一条直线上,若外积小于0则说明xyz向顺时针旋转,令z = y。
  4. 根据外积找到边上所有的点。
  5. 令x = y,重复步骤2、3。
  6. 直到找到最初始的点作为y点,结束。

代码

class Solution:
    def outerTrees(self, trees: List[List[int]]) -> List[List[int]]:

        def cross(x, y, z):  # 求外积
            return (y[0] - x[0]) * (z[1] - y[1]) - (z[0] - y[0]) * (y[1] - x[1])

        n = len(trees)
        if n <= 3:
            return trees

        left = 0
        for i, tree in enumerate(trees):
            if tree[0] < trees[left][0]:
                left = i

        x = left
        visited = set()
        res = []
        while True:
            y = (x + 1) % n
            # 找到最右边的点
            for z in range(n):
                #if z not in visited:
                if cross(trees[x], trees[y], trees[z]) < 0:
                    y = z

            if y not in visited:
                visited.add(y)
                res.append(trees[y])

			# 找到边上所有的点
            for z in range(n):
                if z != x and z != y and cross(trees[x], trees[y], trees[z]) == 0 and z not in visited:
                    visited.add(z)
                    res.append(trees[z])

            if y == left:
                break
            x = y

        return res

三、方法三:Graham算法

时间复杂度:O(nlogn)
空间复杂度:O(n)

算法步骤

  1. 如果元素个数小于等于3个,则全部为凸包上的点,返回全部元素
  2. 找到纵坐标值最小的点,将其作为第0个点。
  3. 以初始点为原点,按照极坐标的角度大小进行排序
  4. 对于凸包最后一条线上的元素按照距离从大到小进行排序
  5. 构造栈,从第二个元素开始遍历,如果当前元素与栈顶的两个元素构成的向量顺时针旋转,则弹出栈顶元素
  6. 返回栈对应的元素。

代码

class Solution:
    def outerTrees(self, trees: List[List[int]]) -> List[List[int]]:

        def cross(x, y, z):  # 求外积
            return (y[0] - x[0]) * (z[1] - y[1]) - (z[0] - y[0]) * (y[1] - x[1])

        def distance(x, y):  # 求距离
            return (y[0] - x[0]) ** 2 + (y[1] - x[1]) ** 2

        n = len(trees)
        if n <= 3:
            return trees

        bottom = 0  # y最小的点
        for i, tree in enumerate(trees):
            if tree[1] < trees[bottom][1]:
                bottom = i
        trees[bottom], trees[0] = trees[0], trees[bottom]

        # 以 bottom 原点,按照极坐标的角度大小进行排序
        def cmp(x: List[int], y: List[int]) -> int:
            diff = cross(trees[0], y, x) - cross(trees[0], x, y)
            return diff if diff else distance(trees[0], x) - distance(trees[0], y)
        trees[1:] = sorted(trees[1:], key=cmp_to_key(cmp))
        #print('trees1:', trees)
        #print(cross([2, 0], [2, 2], [4, 2]))
        #print(cross([2, 0], [2, 2], [3, 3]))

        # 对于凸包最后且在同一条直线的元素按照距离从大到小进行排序
        r = n - 1
        while r >= 0 and cross(trees[0], trees[n - 1], trees[r]) == 0:
            r -= 1
        l, h = r + 1, n - 1
        while l < h:
            trees[l], trees[h] = trees[h], trees[l]
            l += 1
            h -= 1
        #print('trees2:', trees)

        stack = [0, 1]
        for i in range(2, n):
            # 如果当前元素与栈顶的两个元素构成的向量顺时针旋转,则弹出栈顶元素
            while len(stack) > 1 and cross(trees[stack[-2]], trees[stack[-1]], trees[i]) < 0:
                stack.pop()
            stack.append(i)
        return [trees[i] for i in stack]

方法四:Andrew算法(求凸包)

时间复杂度:O(nlogn)
空间复杂度:O(n)
算法步骤

  1. 如果元素个数小于等于3个,则全部为凸包上的点,返回全部元素
  2. 按照 x 从小到大排序,如果 x 相同,则按照 y 从小到大排序
  3. 建立栈,从第一个元素开始遍历,根据外积求凸包的下半部分
  4. 根据外积求凸包的上半部分
  5. 返回栈对应的元素

代码

class Solution:
    def outerTrees(self, trees: List[List[int]]) -> List[List[int]]:
        
        def cross(p: List[int], q: List[int], r: List[int]) -> int:
            return (q[0] - p[0]) * (r[1] - q[1]) - (q[1] - p[1]) * (r[0] - q[0])

        n = len(trees)
        if n < 4:
            return trees

        # 按照 x 从小到大排序,如果 x 相同,则按照 y 从小到大排序
        trees.sort()
        #print('trees1:', trees)

        hull = [0]  # hull[0] 需要入栈两次,不标记
        used = [False] * n
        # 求凸包的下半部分
        for i in range(1, n):
            while len(hull) > 1 and cross(trees[hull[-2]], trees[hull[-1]], trees[i]) < 0:
                used[hull.pop()] = False
            used[i] = True
            hull.append(i)
        #print('trees2:', trees)
        #print('hull1:', hull)

        # 求凸包的上半部分
        m = len(hull)
        for i in range(n - 2, -1, -1):
            if not used[i]:
                while len(hull) > m and cross(trees[hull[-2]], trees[hull[-1]], trees[i]) < 0:
                    used[hull.pop()] = False
                used[i] = True
                hull.append(i)
        #print('trees3:', trees)
        #print('hull2:', hull)
        # hull[0] 同时参与凸包的上半部分检测,因此需去掉重复的 hull[0]
        hull.pop()

        return [trees[i] for i in hull]
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值