Leetcode 963. 最小面积矩形 II 解题思路及C++实现
生活随笔
收集整理的這篇文章主要介紹了
Leetcode 963. 最小面积矩形 II 解题思路及C++实现
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
解題思路:
這道題目的難點在于如何判斷一個矩形,網上也有很多方法。
對于給定的四個點,可以判斷其四個頂點是否是直角,或者先求出中心點,矩形中每個點到中心點的距離是相等的。
下面給出的程序的邏輯是:暴力遍歷每三個頂點,先判斷其是否構成兩條垂直的邊,如果垂直的話,就去找第四個頂點,通過一個 unordered_set 查找,即可知道points數組中是否存在第四個點。
判斷是否垂直:向量內積為0
求第四個點:向量運算
?
class Solution { public:double minAreaFreeRect(vector<vector<int>>& points) {int n = points.size();if(n < 4) return 0;unordered_set<string> h;for(int i = 0; i < points.size(); i++){h.insert(to_string(points[i][0]) + " " + to_string(points[i][1]));}double res = INT_MAX;for(int i = 0; i < n; i++){for(int j = i + 1; j < n; j++){for(int k = j + 1; k < n; k++){update(points[i], points[j], points[k], res, h);update(points[j], points[i], points[k], res, h);update(points[k], points[i], points[j], res, h);}}}if(res == INT_MAX) res = 0;return res;}void update(const vector<int>& x, const vector<int>& y, const vector<int>& z, double& res, const unordered_set<string>& h){int x1 = x[0] - y[0];int y1 = x[1] - y[1];int x2 = x[0] - z[0];int y2 = x[1] - z[1];vector<int> p(2);if(x1*x2 + y1*y2 == 0){p[0] = z[0] - x1;p[1] = z[1] - y1;if(h.find(to_string(p[0]) + " " + to_string(p[1])) != h.end()){res = min(res, sqrt(x1*x1 + y1*y1) * sqrt(x2*x2 + y2*y2));}}} };?
?
?
總結
以上是生活随笔為你收集整理的Leetcode 963. 最小面积矩形 II 解题思路及C++实现的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Leetcode 398. 随机数索引
- 下一篇: Leetcode 88. 合并两个有序数