939. Minimum Area Rectangle

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014110320/article/details/83958137

题目链接

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;
    }
}

猜你喜欢

转载自blog.csdn.net/u014110320/article/details/83958137