问题描述
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;
}
};