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:
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.
本题题意很简单,就是判定是否是正方形,直接统计所有的边长即可
代码如下:
#include <iostream>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <string>
#include <climits>
#include <algorithm>
#include <sstream>
#include <functional>
#include <bitset>
#include <numeric>
#include <cmath>
using namespace std;
class Solution
{
public:
bool validSquare(vector<int>& p1, vector<int>& p2, vector<int>& p3, vector<int>& p4)
{
map<int, int> mmp;
vector<vector<int>> all{p1,p2,p3,p4};
for (int i = 0; i < all.size(); i++)
{
for (int j = i + 1; j < all.size(); j++)
{
int x1 = all[i][0], y1 = all[i][1], x2 = all[j][0], y2 = all[j][1];
int len = (x1 - x2)*(x1 - x2) + (y1 - y2)*(y1 - y2);
if (len == 0)
return false;
mmp[len]++;
}
}
return mmp.size() == 2;
}
};
还没有评论,来说两句吧...