intans= Integer.MAX_VALUE; Map<Integer, Integer> lastx = newHashMap(); for (int x: rows.keySet()) { List<Integer> row = rows.get(x); Collections.sort(row); for (inti=0; i < row.size(); ++i) for (intj= i+1; j < row.size(); ++j) { inty1= row.get(i), y2 = row.get(j); intcode=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; } }
[sol1]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
classSolution(object): defminAreaRect(self, points): columns = collections.defaultdict(list) for x, y in points: columns[x].append(y) lastx = {} ans = float('inf')
for x insorted(columns): column = columns[x] column.sort() for j, y2 inenumerate(column): for i in xrange(j): y1 = column[i] if (y1, y2) in lastx: ans = min(ans, (x - lastx[y1,y2]) * (y2 - y1)) lastx[y1, y2] = x return ans if ans < float('inf') else0
intans= Integer.MAX_VALUE; for (inti=0; i < points.length; ++i) for (intj= i+1; j < points.length; ++j) { if (points[i][0] != points[j][0] && points[i][1] != points[j][1]) { if (pointSet.contains(40001 * points[i][0] + points[j][1]) && pointSet.contains(40001 * points[j][0] + points[i][1])) { ans = Math.min(ans, Math.abs(points[j][0] - points[i][0]) * Math.abs(points[j][1] - points[i][1])); } } }
return ans < Integer.MAX_VALUE ? ans : 0; } }
[sol2]
1 2 3 4 5 6 7 8 9 10 11
classSolution(object): defminAreaRect(self, points): S = set(map(tuple, points)) ans = float('inf') for j, p2 inenumerate(points): for i in xrange(j): p1 = points[i] if (p1[0] != p2[0] and p1[1] != p2[1] and (p1[0], p2[1]) in S and (p2[0], p1[1]) in S): ans = min(ans, abs(p2[0] - p1[0]) * abs(p2[1] - p1[1])) return ans if ans < float('inf') else0