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.

思路:核心思想就是双层遍历,假设两个点分别是左上角(x1, y1)和右下角(x2, y2),看能否找到(x2, y1), (x1, y2),怎么找,那么就是同样的x下面有一系列点,那么就是HashMap<Integer, HashSet<Integer>>来找;注意遍历的时候,双层循环是points.length;

class Solution {
    public int minAreaRect(int[][] points) {
        HashMap<Integer, HashSet<Integer>> hashmap = new HashMap<>();
        for(int[] point: points) {
            int x = point[0];
            int y = point[1];
            hashmap.putIfAbsent(x, new HashSet<Integer>());
            hashmap.get(x).add(y);
        }
        
        int res = Integer.MAX_VALUE;
        int n = points.length;
        for(int i = 0; i < n; i++) {
            for(int j = i + 1; j < n; j++) {
                int x1 = points[i][0];
                int y1 = points[i][1];
                
                int x2 = points[j][0];
                int y2 = points[j][1];
                
                if(x1 == x2 || y1 == y2) {
                    continue;
                }
                if(hashmap.get(x1).contains(y2) && hashmap.get(x2).contains(y1)) {
                    res = Math.min(res, Math.abs(x1 - x2) * Math.abs(y1 - y2));
                }
            }
        }
        return res == Integer.MAX_VALUE ? 0 : res;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值