最小面积矩形
题目描述
给定在 xy 平面上的一组点,确定由这些点组成的矩形的最小面积,其中矩形的边平行于 x 轴和 y 轴。
如果没有任何矩形,就返回 0。
示例 1:
输入:[[1,1],[1,3],[3,1],[3,3],[2,2]]
输出:4
示例 2:
输入:[[1,1],[1,3],[3,1],[3,3],[4,1],[4,3]]
输出:2
提示:
- 1 <= points.length <= 500
- 0 <= points[i][0] <= 40000
- 0 <= points[i][1] <= 40000
- 所有的点都是不同的。
官方题解-枚举对角线
题解链接
面试考到了这道题,没做出来,这种题就是做过一次就不会忘的那种。
代码
class Solution {
public int minAreaRect(int[][] points) {
Set<Integer> set = new HashSet<>();
for (int[] point : points) {
//让每个点对应集合中唯一的值,因为0 <= x,y <= 40000
set.add(40001 * point[0] + point[1]);
}
//结果
int res = Integer.MAX_VALUE;
//数组行数
int lenx = points.length;
for (int i = 0; i < lenx; i++) {
for (int j = i + 1; j < lenx; j++) {
//判断两个点不在同一行且不在同一列
if (points[i][0] != points[j][0] && points[i][1] != points[j][1]) {
//判断矩形的另外两个点是否存在。
if (set.contains(40001 * points[i][0] + points[j][1]) && set.contains(40001 * points[j][0] + points[i][1])) {
res = Math.min(res, Math.abs(points[i][0] - points[j][0]) * Math.abs(points[i][1] - points[j][1]));
}
}
}
}
//结果为Integer.MAX_VALUE说明矩形不存在,返回0
return res == Integer.MAX_VALUE ? 0 : res;
}
}
时间复杂度
O(n^2)