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 <= points.length <= 500
0 <= points[i][0] <= 40000
0 <= points[i][1] <= 40000
- All points are distinct.
思路:这个题给的都是整点,也就是说出现的长方形只可能是平行于x,平行于y。
所以,全部放set里,枚举对角线上的两个点即可。
代码:
#include <bits/stdc++.h>
typedef long long ll;
using namespace std;
class Solution {
public:
int minAreaRect(vector<vector<int>>& points) {
set<pair<int,int> > se;
for(auto &t : points)
{
se.insert(make_pair(t[0],t[1]));
}
int n= points.size();
int M= 1e9+7;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
int x1= points[i][0],y1=points[i][1],x2=points[j][0],y2=points[j][1];
if(x1==x2||y1==y2) continue;
if(abs(x2-x1)*abs(y2-y1)>M) continue;
if(se.find(make_pair(x1,y2))!=se.end()&&(se.find(make_pair(x2,y1))!=se.end()))
{
M= min(M,abs(x2-x1)*abs(y2-y1));
}
}
}
if(M==1e9+7)
{
return 0;
}
return M;
}
};