Minimum Area Rectangle LeetCode solution in C++

1
class Solution {
2
public:
3
int minAreaRect(vector<vector<int>> &points) {
4
unordered_map<int, unordered_set<int>> pts;
5
for (auto p : points) {
6
pts[p[0]].insert(p[1]);
7
}
8

9
int minArea = INT_MAX;
10
int n = points.size();
11
for (int i = 0; i < n; i++) {
12
for (int j = i + 1; j < n; j++) {
13
auto p1 = points[i];
14
auto p2 = points[j];
15
if (pts[p1[0]].size() < 2 || pts[p2[0]].size() < 2) continue; // added to avoid extra loop
16
if (p1[0] != p2[0] && p1[1] != p2[1]) {
17
if (pts[p1[0]].count(p2[1]) > 0 && pts[p2[0]].count(p1[1]) > 0) {
18
minArea = min(minArea, (abs(p1[0] - p2[0]) * abs(p1[1] - p2[1])));
19
}
20
}
21
}
22
}
23
return minArea == INT_MAX ? 0 : minArea;
24
}
25
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0