1. 程式人生 > >Leetcode963. Minimum Area Rectangle II最小面積矩形2

Leetcode963. Minimum Area Rectangle II最小面積矩形2

給定在 xy 平面上的一組點,確定由這些點組成的任何矩形的最小面積,其中矩形的邊不一定平行於 x 軸和 y 軸。

如果沒有任何矩形,就返回 0。

示例 1:

輸入:[[1,2],[2,1],[1,0],[0,1]] 輸出:2.00000 解釋:最小面積的矩形出現在 [1,2],[2,1],[1,0],[0,1] 處,面積為 2。

 

示例 2:

輸入:[[0,1],[2,1],[1,1],[1,0],[2,0]] 輸出:1.00000 解釋:最小面積的矩形出現在 [1,0],[1,1],[2,1],[2,0] 處,面積為 1。

示例 3:

 

輸入:[[0,3],[1,2],[3,1],[1,3],[2,1]] 輸出:0 解釋:沒法從這些點中組成任何矩形。

示例 4:

輸入:[[3,1],[1,1],[0,1],[2,1],[3,3],[3,2],[0,2],[2,3]] 輸出:2.00000 解釋:最小面積的矩形出現在 [2,1],[2,3],[3,3],[3,1] 處,面積為 2。

 

提示:

  1. 1 <= points.length <= 50
  2. 0 <= points[i][0] <= 40000
  3. 0 <= points[i][1] <= 40000
  4. 所有的點都是不同的。
  5. 與真實值誤差不超過 10^-5 的答案將視為正確結果。

 

該題有很多需要注意的地方。

 

首先注意題目說的是矩形,而不是正方形。

 

然後 注意返回值是double型,所以我們要在題中使用double型別。

 

double型別是靠精度來比較的,而不是 == 

 

矩形的特徵就是:對角線相等且平分

 

用其他方法要注意題中3個點在一條直線上的情況

 

這種多重迴圈的題,比如該題一般來說是n*n*n*n,我們可以優化成n*n*n。

 

const double esp = 1e-7;
class Solution {
 public:
	 double minAreaFreeRect(vector<vector<int>>& points) 
	 {
		 int len = points.size();
		 if (len < 4)
			 return 0;
		 double ans = -1;
         map<pair<double, double>, bool> check;
         for(int i = 0; i < len; i++)
         {
            check[make_pair(points[i][0], points[i][1])] = true;
         }
         
		 for (int i = 0; i < len; i++)
		 {
             double x1 = points[i][0], y1 = points[i][1];
			 for (int j = 0; j < len; j++)
			 {
                 if(i == j)
                    continue;
                double x2 = points[j][0], y2 = points[j][1];
				for (int k = 0; k < len; k++)
				{
                    if(k == i || k == j)
                        continue;
                    double x3 = points[k][0], y3 = points[k][1];
                    double dis = GetDis(x1, y1, x2, y2);
//中點
                    double midx = (x1 + x2) * 1.0 / 2;
                    double midy = (y1 + y2) * 1.0 / 2;
                    if(abs(dis - GetDis(midx, midy, x3, y3) * 2) < esp)
                    {
                        double x4 = 2 * midx - x3;
                        double y4 = 2 * midy - y3;
                        if(check[make_pair(x4, y4)] == true)
                        {
                            double l = GetDis(x1, y1, x3, y3);
                            double w = GetDis(x1, y1, x4, y4);
                            double area = l * w;
                            ans = ans < 0? area : min(area, ans);
                        }
                    }
                }
             }
         }
         return ans < 0? 0 : ans;
     }
//求距離
     double GetDis(double x1, double y1, double x2, double y2)
     {
         return sqrt((x1 - x2)*(x1 - x2) + (y1 - y2)*(y1 - y2));
     }
 };