原题:
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.
思路:题目的大意是给出四个点的坐标,判断这四个点能否构成正方形。(1)计算p2,p3,p4到p1的距离并排序。(2)若出现以下两种情况,则判定为非正方形:某个点到p1的距离为0;p2,p3,p4到p1的距离排序之后为d1,d2,d3;若d1!=d2,(d1^2+d2^2)!=d3^2。(3)设距离p1最远的点为p’,p’到另外两个点的距离也必须为边长。
代码:
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);
//计算p2,p3,p4到p1的距离并排序
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));
//c++中sort排序的时候优先比较pair.first,然后比较pair.second
sort(d_to_p1.begin(),d_to_p1.end());
//若出现以下两种情况,则判定为非正方形:(1)某个点到p1的距离为0(2)p2,p3,p4到p1的距离排序之后为d1,d2,d3;若d1!=d2,(d1^2+d2^2)!=d3^2
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;
//设距离p1最远的点为p',p'到另外两个点的距离也必须为边长
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;
}
};