[leetcode] 963. Minimum Area Rectangle II

Description

Given a set of points in the xy-plane, determine the minimum area of any rectangle formed from these points, with sides not necessarily parallel to the x and y axes.

If there isn’t any rectangle, return 0.

Example 1:
在这里插入图片描述

Input: [[1,2],[2,1],[1,0],[0,1]]
Output: 2.00000
Explanation: The minimum area rectangle occurs at [1,2],[2,1],[1,0],[0,1], with an area of 2.

Example 2:

Input: [[0,1],[2,1],[1,1],[1,0],[2,0]]
Output: 1.00000
Explanation: The minimum area rectangle occurs at [1,0],[1,1],[2,1],[2,0], with an area of 1.

Example 3:

Input: [[0,3],[1,2],[3,1],[1,3],[2,1]]
Output: 0
Explanation: There is no possible rectangle to form from these points.

Example 4:

Input: [[3,1],[1,1],[0,1],[2,1],[3,3],[3,2],[0,2],[2,3]]
Output: 2.00000
Explanation: The minimum area rectangle occurs at [2,1],[2,3],[3,3],[3,1], with an area of 2.

Note:

  1. 1 <= points.length <= 50
  2. 0 <= points[i][0] <= 40000
  3. 0 <= points[i][1] <= 40000
  4. All points are distinct.
  5. Answers within 10^-5 of the actual value will be accepted as correct.

分析

题目的意思是:给定很多坐标点,找出能够围成的最小矩形的面积。我参考了一下别人的思路,暴力求解主要是用的直角三角形的向量正交的原理,所以利用三重循环找出两个正交向量,然后再求与该直角三角形构成矩形的第四个点是否在points中。如果满足就更新最小区域面积res就行了。注意所有的点可能都不构成矩形,所以最后要判断一下,res未更改的话,就返回0,否则返回res.

代码

class Solution:
    def minAreaFreeRect(self, points: List[List[int]]) -> float:
        n=len(points)
        pos=[]
        res=float('inf')
        for i in range(n):
            for j in range(i+1,n):
                x1=points[j][0]-points[i][0]
                y1=points[j][1]-points[i][1]
                for k in range(j+1,n):
                    x2=points[k][0]-points[i][0]
                    y2=points[k][1]-points[i][1]
                    x3=points[i][0]+x1+x2
                    y3=points[i][1]+y1+y2
                    if([x3,y3] in points and x1*x2+y2*y1==0):
                        res=min(res,abs(x1*y2-x2*y1))
        if(res==float('inf')):
            return 0
        return res

参考文献

Python 枚举正交的向量,利用向量外积求矩形面积 简单粗暴

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值