[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.

最小面积矩形。

给定在 xy 平面上的一组点,确定由这些点组成的矩形的最小面积,其中矩形的边平行于 x 轴和 y 轴。如果没有任何矩形,就返回 0。

这是一道数学题,具体思路如下。因为题目要求的是找一个矩形的最小面积,同时这个矩形的四条边要与X轴和Y轴平行,所以如果你只找到同一条边上的两个点,你顶多只能确定一条边。所以这里优化的思路是,先把所有的点存入hashmap,存入的方式是<横坐标, hashset<纵坐标>>。

然后我们用两个for循环扫描所有的点,我们对于所有的点,只要这两个点的横纵坐标都不同(则说明这两个点一定不在同一条与X轴或与Y轴平行的直线上),则我们把这两个点当做能形成矩形的四个点中的两个对角线上的点。找到这两个点之后,我们再去hashmap中找另一条对角线上的两个点在hashmap中是否存在,若存在则可以计算面积了。这个找对角线的思路在593题也有体现。

时间O(n^2)

空间O(n)

Java实现

 1 class Solution {
 2     public int minAreaRect(int[][] points) {
 3         Map<Integer, Set<Integer>> map = new HashMap<>();
 4         // <横坐标,纵坐标>
 5         for (int[] p : points) {
 6             if (!map.containsKey(p[0])) {
 7                 map.put(p[0], new HashSet<>());
 8             }
 9             map.get(p[0]).add(p[1]);
10         }
11 
12         int min = Integer.MAX_VALUE;
13         for (int[] p1 : points) {
14             for (int[] p2 : points) {
15                 // if have the same x or y
16                 if (p1[0] == p2[0] || p1[1] == p2[1]) {
17                     continue;
18                 }
19                 // 找对角线上的两个点
20                 if (map.get(p1[0]).contains(p2[1]) && map.get(p2[0]).contains(p1[1])) {
21                     min = Math.min(min, Math.abs(p1[0] - p2[0]) * Math.abs(p1[1] - p2[1]));
22                 }
23             }
24         }
25         return min == Integer.MAX_VALUE ? 0 : min;
26     }
27 }

 

相关题目

593. Valid Square

939. Minimum Area Rectangle - 也是涉及找对角线的数学题

LeetCode 题目总结

posted @ 2020-11-04 02:01  CNoodle  阅读(124)  评论(0编辑  收藏  举报