Given the coordinates of four points in 2D space, return whether the four points could construct a square.
The coordinate (x,y) of a point is represented by an integer array with two integers.
Example:
Input: p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,1] Output: True
Note:
- All the input integers are in the range [-10000, 10000].
- A valid square has four equal sides with positive length and four equal angles (90-degree angles).
- Input points have no order.
這道題給了我們四個點,讓驗證這四個點是否能組成一個正方形,剛開始博主考慮的方法是想判斷四個角是否是直角,但即便四個角都是直角,也不能說明一定就是正方形,還有可能是矩形。還得判斷各邊是否相等。其實這里可以僅通過邊的關系的來判斷是否是正方形,根據初中幾何的知識可以知道正方形的四條邊相等,兩條對角線相等,滿足這兩個條件的四邊形一定是正方形。那么這樣就好辦了,只需要對四個點,兩兩之間算距離,如果計算出某兩個點之間距離為0,說明兩點重合了,直接返回 false,如果不為0,那么就建立距離和其出現次數之間的映射,最后如果我們只得到了兩個不同的距離長度,那么就說明是正方形了,參見代碼如下:
解法一:
class Solution { public: bool validSquare(vector<int>& p1, vector<int>& p2, vector<int>& p3, vector<int>& p4) { unordered_map<int, int> m; vector<vector<int>> v{p1, p2, p3, p4}; for (int i = 0; i < 4; ++i) { for (int j = i + 1; j < 4; ++j) { int x1 = v[i][0], y1 = v[i][1], x2 = v[j][0], y2 = v[j][1]; int dist = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2); if (dist == 0) return false; ++m[dist]; } } return m.size() == 2; } };
我們其實不用建立映射,直接用個集合 HashSet 來放距離就行了,如果最后集合中不存在0,且里面只有兩個數的時候,說明是正方形,參見代碼如下:
解法二:
class Solution { public: bool validSquare(vector<int>& p1, vector<int>& p2, vector<int>& p3, vector<int>& p4) { unordered_set<int> s{d(p1, p2), d(p1, p3), d(p1, p4), d(p2, p3), d(p2, p4), d(p3, p4)}; return !s.count(0) && s.size() == 2; } int d(vector<int>& p1, vector<int>& p2) { return (p1[0] - p2[0]) * (p1[0] - p2[0]) + (p1[1] - p2[1]) * (p1[1] - p2[1]); } };
參考資料:
https://leetcode.com/problems/valid-square/
https://leetcode.com/problems/valid-square/discuss/103442/c-3-lines-unordered_set