593. Valid Square

https://leetcode.com/problems/valid-square/

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:

  1. All the input integers are in the range [-10000, 10000].

  2. A valid square has four equal sides with positive length and four equal angles (90-degree angles).

  3. Input points have no order.

检验二维笛卡尔坐标系上的四个点能否构成正方形。满足四边相等和两个对角线相等就是正方形。

答案参考了

/*
 * @lc app=leetcode id=593 lang=cpp
 *
 * [593] Valid Square
 */

// @lc code=start
class Solution {
public:
    bool validSquare(vector<int>& p1, vector<int>& p2, vector<int>& p3, vector<int>& p4) {
        const auto dist = [](vector<int> &a, vector<int> &b) {
            return (a[0] - b[0]) * (a[0] - b[0]) + (a[1] - b[1]) * (a[1] - b[1]);
        };
        vector<vector<int>> v({p1, p2, p3, p4});
        unordered_set<int> s;
        for (int i = 0; i < 4; ++i) {
            for (int j = 0; j < i; ++j) {
                s.insert(dist(v[i], v[j]));
            }
        } 
        return s.size() == 2 && !s.count(0);
    }
};
// @lc code=end

Last updated