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.
A:
根据4个边相等。对角线是 sqrt(2)的关系。
class Solution { public: bool validSquare(vector<int>& p1, vector<int>& p2, vector<int>& p3, vector<int>& p4) { if(p1[0] == p2[0] and p2[0] == p3[0]) // if they are same return false; vector<int> V; V.push_back(getLen2(p1,p2)); V.push_back(getLen2(p1,p3)); V.push_back(getLen2(p1,p4)); V.push_back(getLen2(p2,p3)); V.push_back(getLen2(p2,p4)); V.push_back(getLen2(p3,p4)); sort(V.begin(), V.end()); bool first4Equal = V[0] == V[1] and V[1] == V[2] and V[2] == V[3]; bool last2Equal = V[4] == V[5]; bool time2 = V[0] * 2 == V[5]; return first4Equal && last2Equal && time2; } private: int getLen2(vector<int> & p1, vector<int> & p2) { int a = p1[0] - p2[0]; int b = p1[1] - p2[1]; return a*a + b * b; } };
No comments:
Post a Comment