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.
思路:核心思想就是双层遍历,假设两个点分别是左上角(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;
}
}