【LeetCode】验证4个点是否构成正方形

该博客讨论了如何验证二维空间中的四个点是否可以构成一个正方形。根据给定的坐标,通过计算两两之间的距离来确定是否满足正方形的条件——四边等长且角度为90度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题描述

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.

转至原题

解题思路

给点4个坐标点,要求判断是否能构成正方形。值得注意的是4个点不一定按顺序,可以计算两两之间的距离,如果是正方形,距离只有2个值

代码

class Solution {
public:
    int distance(vector<int>& p1, vector<int>& p2){
        return pow(p1[0]-p2[0],2)+pow(p1[1]-p2[1],2);
    }
    bool validSquare(vector<int>& p1, vector<int>& p2, vector<int>& p3, vector<int>& p4) {
        vector<vector<int>> points;
        points.push_back(p1);
        points.push_back(p2);
        points.push_back(p3);
        points.push_back(p4);
        vector<pair<int,int>> d_to_p1;
        d_to_p1.push_back(make_pair(distance(p1,p2),2-1));
        d_to_p1.push_back(make_pair(distance(p1,p3),3-1));
        d_to_p1.push_back(make_pair(distance(p1,p4),4-1));
        sort(d_to_p1.begin(),d_to_p1.end());
        if((d_to_p1[0].first!=d_to_p1[1].first)||(d_to_p1[2].first!=(d_to_p1[1].first+d_to_p1[0].first))||(d_to_p1[0].first==0))
            return false;
        int distance1=distance(points[d_to_p1[2].second],points[d_to_p1[1].second]);
        int distance2=distance(points[d_to_p1[2].second],points[d_to_p1[0].second]);
        if((distance1!=distance2)||(distance1!=d_to_p1[0].first))
            return false;
        return true;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值