1. 程式人生 > >LeetCode 939. Minimum Area Rectangle(暴力)

LeetCode 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.

 

思路:這個題給的都是整點,也就是說出現的長方形只可能是平行於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;
    }
    
};