问题:给定在 xy 平面上的一组点,确定由这些点组成的矩形的最小面积,其中矩形的边平行于 x 轴和 y 轴。
如果没有任何矩形,就返回 0。
示例:
输入:[[1,1],[1,3],[3,1],[3,3],[2,2]]
输出:4
输入:[[1,1],[1,3],[3,1],[3,3],[4,1],[4,3]]
输出:2
public class SixDay {
public static void main(String[] args) {
int[][] nums={{1,1}, {1,3},{3,1},{3,3},{2,2}};
int areaNum = getAreaNum(nums);
System.out.println(areaNum);
}
public static int getAreaNum(int[][] points) {
Map<Integer, List<Integer>> rows = new TreeMap();
for (int[] point : points) {
int x = point[0], y = point[1];
rows.computeIfAbsent(x, z -> new ArrayList()).add(y);
}
int ans = Integer.MAX_VALUE;
Map<Integer, Integer> lastx = new HashMap();
for (int x : rows.keySet()) {
List<Integer> row = rows.get(x);
Collections.sort(row);
for (int i = 0; i < row.size(); ++i)
for (int j = i + 1; j < row.size(); ++j) {
int y1 = row.get(i), y2 = row.get(j);
int code = 40001 * y1 + y2;
if (lastx.containsKey(code))
ans = Math.min(ans, (x - lastx.get(code)) * (y2 - y1));
lastx.put(code, x);
}
}
return ans < Integer.MAX_VALUE ? ans : 0;
}
}
参考链接:https://leetcode.cn/problems/minimum-area-rectangle/