939. Minimum Area Rectangle

本文解析了在二维平面上,由给定点集确定的最小矩形面积算法。通过两个对角点确定矩形,遍历所有可能的点对,找到最小面积。代码示例清晰展示了算法实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接

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 <= points.length <= 500
0 <= points[i][0] <= 40000
0 <= points[i][1] <= 40000
All points are distinct.

这题我的思路是由三个点确定一个长方形,但是在解题过程中,由于自己思路不够清晰,最后没有做出来。最后答案的思路是两点(对角线)确定一个长方形,遍历所以可能的点对,最后找到最小的。下面是解题代码,代码比较容易看懂。

class Solution {
    public int minAreaRect(int[][] points) {
        int min = Integer.MAX_VALUE;
        Map<Integer, List<Integer>> x2y = new HashMap<>(); //将x相同的点,其y放在一个列表中
        //下面是x2y的初始化过程
        for(int[] point : points) {
        	if(!x2y.containsKey(point[0])) {
        		List<Integer> list = new ArrayList<Integer>();
        		list.add(point[1]);
        		x2y.put(point[0], list);
        	}else {
        		x2y.get(point[0]).add(point[1]);
        	}
        }
        int len = points.length;
        for(int i = 1; i < len; i++) {
        	for(int j = i - 1; j >=0; j--) {
        		if(points[i][0] == points[j][0] || points[i][1] == points[j][1]) {
        			continue;
        		}
        		int x1 = points[i][0];
        		int y1 = points[i][1];
        		int x2 = points[j][0];
        		int y2 = points[j][1];
        		if(x2y.get(x1).contains(y2) && x2y.get(x2).contains(y1)) { //如果能找到这样的长方形,计算其面积
        			min = Math.min(min, Math.abs(x1 - x2) * Math.abs(y1- y2));
        		}
        	}
        }
        if(min == Integer.MAX_VALUE) {
        	return 0;
        }
        return min;
    }
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值