You are given an array of points in the X-Y plane points where
points[i] = [xi, yi].
Return the minimum area of a rectangle formed from these points, with sides parallel to the X and Y axes. If there is not any such rectangle, return 0.
To find the minimum area rectangle, we need to find two pairs of points that share the same x or y coordinates and form the opposite corners of a rectangle. By storing all points in a set, we can efficiently check if the other two corners exist for each pair of points.
For each pair of points, if they are not on the same line (x1 ≠ x2 and y1 ≠ y2), check if the other two corners (x1, y2) and (x2, y1) exist in the set.
If so, compute the area and update the minimum area found.
Return the minimum area, or 0 if no rectangle is found.
classSolution {
publicintminAreaRect(int[][] points) {
Set<String> st =new HashSet<>();
for (int[] p : points) st.add(p[0]+","+ p[1]);
int ans = Integer.MAX_VALUE;
for (int i = 0; i < points.length; ++i) {
for (int j = i+1; j < points.length; ++j) {
int x1 = points[i][0], y1 = points[i][1];
int x2 = points[j][0], y2 = points[j][1];
if (x1 != x2 && y1 != y2) {
if (st.contains(x1+","+y2) && st.contains(x2+","+y1)) {
ans = Math.min(ans, Math.abs(x1-x2)*Math.abs(y1-y2));
}
}
}
}
return ans == Integer.MAX_VALUE? 0 : ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
classSolution {
funminAreaRect(points: Array<IntArray>): Int {
val st = mutableSetOf<Pair<Int,Int>>()
for (p in points) st.add(p[0] to p[1])
var ans = Int.MAX_VALUE
for (i in points.indices) {
for (j in i+1 until points.size) {
val(x1, y1) = points[i]
val(x2, y2) = points[j]
if (x1 != x2 && y1 != y2) {
if ((x1 to y2) in st && (x2 to y1) in st) {
ans = minOf(ans, kotlin.math.abs(x1-x2)*kotlin.math.abs(y1-y2))
}
}
}
}
returnif (ans ==Int.MAX_VALUE) 0else ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
defmin_area_rect(points: list[list[int]]) -> int:
st = set((x, y) for x, y in points)
ans = float('inf')
for i in range(len(points)):
for j in range(i+1, len(points)):
x1, y1 = points[i]
x2, y2 = points[j]
if x1 != x2 and y1 != y2:
if (x1, y2) in st and (x2, y1) in st:
area = abs(x1-x2) * abs(y1-y2)
ans = min(ans, area)
return0if ans == float('inf') else ans
impl Solution {
pubfnmin_area_rect(points: Vec<Vec<i32>>) -> i32 {
use std::collections::HashSet;
let st: HashSet<(i32,i32)>= points.iter().map(|p| (p[0], p[1])).collect();
letmut ans =i32::MAX;
for i in0..points.len() {
for j in i+1..points.len() {
let (x1, y1) = (points[i][0], points[i][1]);
let (x2, y2) = (points[j][0], points[j][1]);
if x1 != x2 && y1 != y2 {
if st.contains(&(x1, y2)) && st.contains(&(x2, y1)) {
let area = (x1-x2).abs() * (y1-y2).abs();
ans = ans.min(area);
}
}
}
}
if ans ==i32::MAX { 0 } else { ans }
}
}