LeetCode #939 - Minimum Area Rectangle

题目描述:

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

If there isn't any rectangle, return 0.

Example 1:

Input: [[1,1],[1,3],[3,1],[3,3],[2,2]]

Output: 4

Example 2:

Input: [[1,1],[1,3],[3,1],[3,3],[4,1],[4,3]]

Output: 2

Note:

1. 1 <= points.length <= 500

2. 0 <= points[i][0] <= 40000

3. 0 <= points[i][1] <= 40000

4. All points are distinct.

class Solution {
public:
    int minAreaRect(vector<vector<int>>& points) {
        unordered_map<int,bool> hash;
        // unordered_map不支持用pair做key,所以为了映射xy坐标,可以令(x*40001+y)做key,因为x/y<=40000
        for(int i=0;i<points.size();i++) hash[points[i][0]*40001+points[i][1]]=true;
        int result=INT_MAX;
        for(int i=0;i<points.size();i++)
        {
            for(int j=i+1;j<points.size();j++)
            {
                // 寻找一条对角线,必须横坐标且纵坐标不同
                if(points[i][0]==points[j][0]||points[i][1]==points[j][1]) continue;
                if(hash.count(points[i][0]*40001+points[j][1])&&hash.count(points[j][0]*40001+points[i][1]))
                { // 找到一条对角线之后,判断另一条对角线上的两个点是否存在
                    int area=abs(points[i][0]-points[j][0])*abs(points[i][1]-points[j][1]);
                    result=min(result,area);
                }
            }
        }
        if(result==INT_MAX) return 0;
        else return result;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值