[Leetcode] 593. 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.

思路

首先复习一下如何判定一个四边形是正方形:1)两对对边平行且相等的四边形是平行四边形;2)有一个内角为90°的平行四边形是矩形;3)临边相等的矩形是正方形。

具体到这道题目,我们首先判断由p1, p2, p3, p4顺次构成的四边形是否是平行四边形(通过判断两个对边构成的向量是否相等实现),然后判断是否是长方形(通过判断相邻的边构成的两个向量的内积是否为0来实现);最后判断是否是正方形(通过判断相邻边的边长是否相等来实现)。

由于题目中给出的p1, p2, p3, p4是无序的,所以我们需要分别判断(p1, p2, p3, p4), (p1, p2, p4, p3)和(p1, p3, p2, p4)顺次相连是否可以构成正方形。只要有一个可以构成,就返回true。

代码

class Solution {
public:
    bool validSquare(vector<int>& p1, vector<int>& p2, vector<int>& p3, vector<int>& p4) {
        if (isValid(p1, p2, p3, p4)) {  // check whether p1, p2, p3, p4 could form the square
            return true;
        }
        if (isValid(p1, p3, p2, p4)) {  // check whether p1, p3, p2, p4 could form the square
            return true;
        }
        if (isValid(p1, p2, p4, p3)) {  // check whether p1, p2, p4, p3 could form the square
            return true;
        }
        return false;
    }
private:
    int dotProduct(vector<int> &v1, vector<int> &v2) {
        return v1[0] * v2[0] + v1[1] * v2[1];
    }
    int squaredLength(vector<int> &v) {
        return dotProduct(v, v);
    }
    bool isValid(vector<int> &p1, vector<int> &p2, vector<int> &p3, vector<int> &p4) {
        // check whether p1, p2, p3, p4 could form the square
        vector<int> v1 = getVector(p1, p2), v2 = getVector(p4, p3);
        if (v1 != v2) {
            return false;
        }
        v1 = getVector(p1, p4), v2 = getVector(p2, p3);
        if (v1 != v2) {
            return false;
        }
        v2 = getVector(p1, p2);
        int sl1 = squaredLength(v1), sl2 = squaredLength(v2);
        return dotProduct(v1, v2) == 0 && sl1 == sl2 && sl1 > 0;
    }
    vector<int> getVector(vector<int> &p1, vector<int> &p2) {
        return {p2[0] - p1[0], p2[1] - p1[1]};
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值