# 939. Minimum Area Rectangle

Given a set of points in the xy-plane, determine the minimum area of a rectangle formed from these points, with sides parallel to the x and y axes.

If there isn’t any rectangle, return 0.

Example 1:

``````Input: [[1,1],[1,3],[3,1],[3,3],[2,2]]
Output: 4
``````

Example 2:

``````Input: [[1,1],[1,3],[3,1],[3,3],[4,1],[4,3]]
Output: 2
``````

Note:

1. `1 <= points.length <= 500`
2. `0 <= points[i][0] <= 40000`
3. `0 <= points[i][1] <= 40000`
4. All points are distinct.

``````class Solution {
public:
int minAreaRect(vector<vector<int>>& points) {
int res = INT_MAX, n = points.size();
unordered_map<int, unordered_set<int>> m;
for (auto point : points) {
m[point[0]].insert(point[1]);
}
for (int i = 0; i < n; ++i) {
for (int j = i + 1; j < n; ++j) {
if (points[i][0] == points[j][0] || points[i][1] == points[j][1]) continue;
if (m[points[i][0]].count(points[j][1]) && m[points[j][0]].count(points[i][1])) {
res = min(res, abs(points[i][0] - points[j][0]) * abs(points[i][1] - points[j][1]));
}
}
}
return res == INT_MAX ? 0 : res;
}
};
``````

Github 同步地址:

https://github.com/grandyang/leetcode/issues/939

https://leetcode.com/problems/minimum-area-rectangle/

https://leetcode.com/problems/minimum-area-rectangle/discuss/192025/Java-N2-Hashmap

https://leetcode.com/problems/minimum-area-rectangle/discuss/192026/C%2B%2B-hashmap-%2B-set-intersection

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation