LC 963. Minimum Area Rectangle II

Posted ethanhong

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LC 963. Minimum Area Rectangle II相关的知识,希望对你有一定的参考价值。

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

If there isn‘t any rectangle, return 0.

 

Example 1:

Input: [[1,2],[2,1],[1,0],[0,1]]
Output: 2.00000
Explanation: The minimum area rectangle occurs at [1,2],[2,1],[1,0],[0,1], with an area of 2.

Input: [[0,1],[2,1],[1,1],[1,0],[2,0]]
Output: 1.00000
Explanation: The minimum area rectangle occurs at [1,0],[1,1],[2,1],[2,0], with an area of 1.

这题也卡住了,主要是如何判断平面上4个点是矩形?

可以先判断它是个平行四边形,然后判断它的一个角是90度。

x0,x1,x2,x3
y0,y1,y2,y3

首先在不知道顺序的情况下,需要用全部的次序遍历。就是说1,2,3,4; 1,2,4,3;1,4,2,3;1,4,3,2的全排列。

其次判断直角。


#define ALL(x) (x).begin(), (x).end()
#define FOR(i, a, b) for (remove_cv<remove_reference<decltype(b)>::type>::type i = (a); i < (b); i++)
#define REP(i, n) FOR(i, 0, n)

class Solution {
public:
 double minAreaFreeRect(vector<vector<int>>& points) {
   unordered_map<int, unordered_set<int>> c;
   for (auto &x:points)c[x[0]].insert(x[1]);
   long n = points.size(), x0, y0, x1, y1,x2,y2,x3,y3, r = LONG_MAX;
   REP(i, n) {
     x0 = points[i][0]; y0 = points[i][1];
     REP(j, n) {
       x1 = points[j][0]; y1 = points[j][1];
       REP(k, n)
       if (k != i && k != j) {
         x2 = points[k][0]; y2 = points[k][1];
         REP(l, n)
         if (l != i && l != j && l != k) {
           x3 = points[l][0]; y3 = points[l][1];
           if (x1-x0==x2-x3 && y1-y0==y2-y3 && x3-x0==x2-x1 && y3-y0==y2-y1)
             if ((x1-x0)*(x3-x0)+(y1-y0)*(y3-y0)==0)
               r = min(r, abs((x1 - x0) * (y3 - y0) - (y1 - y0) * (x3 - x0)));
         }
       }
     }
   }
   return r == LONG_MAX ? 0 : r;
 }

};

 



























以上是关于LC 963. Minimum Area Rectangle II的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 939. Minimum Area Rectangle

[LC] 76. Minimum Window Substring

[LC] 64. Minimum Path Sum

LC76 Minimum Window Substring

LC.153.Find Minimum in Rotated Sorted Array

LeetCode - Minimum Area Rectangle