leetcode 939. Minimum Area Rectangle
I hate geometric problems…...
class Solution {
public int minAreaRect(int[][] points) {
Map<Integer, List<Integer>> xmap = new HashMap<>();
Map<Integer, List<Integer>> ymap = new HashMap<>();
Set<String> s = new HashSet<>();
for (int i = 0; i < points.length; ++i) {
List<Integer> x = xmap.getOrDefault(points[i][0], new ArrayList<>());
List<Integer> y = ymap.getOrDefault(points[i][1], new ArrayList<>());
x.add(i);
y.add(i);
xmap.put(points[i][0], x);
ymap.put(points[i][1], y);
s.add(Arrays.toString(points[i]));
}
int[] tmp = new int[2];
int ret = Integer.MAX_VALUE;
for (int i = 0; i < points.length; ++i) {
for (Integer right: ymap.getOrDefault(points[i][1], new ArrayList<>())) {
if (points[right][0] <= points[i][0]) continue;
for (Integer up: xmap.getOrDefault(points[i][0], new ArrayList<>())) {
if (points[up][1] <= points[i][1]) continue;
tmp[0] = points[right][0];
tmp[1] = points[up][1];
if (s.contains(Arrays.toString(tmp))) {
//compute size
ret = Math.min(ret, (tmp[0] - points[i][0]) * (tmp[1] - points[i][1]));
}
}
}
}
return ret == Integer.MAX_VALUE? 0: ret;
}
}