leetcode 593. Valid Square 正方形的判定 + 统计边长 + 想法不错

短命女 2022-06-03 04:45 255阅读 0赞

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. #include <iostream>
  2. #include <vector>
  3. #include <map>
  4. #include <set>
  5. #include <queue>
  6. #include <stack>
  7. #include <string>
  8. #include <climits>
  9. #include <algorithm>
  10. #include <sstream>
  11. #include <functional>
  12. #include <bitset>
  13. #include <numeric>
  14. #include <cmath>
  15. using namespace std;
  16. class Solution
  17. {
  18. public:
  19. bool validSquare(vector<int>& p1, vector<int>& p2, vector<int>& p3, vector<int>& p4)
  20. {
  21. map<int, int> mmp;
  22. vector<vector<int>> all{p1,p2,p3,p4};
  23. for (int i = 0; i < all.size(); i++)
  24. {
  25. for (int j = i + 1; j < all.size(); j++)
  26. {
  27. int x1 = all[i][0], y1 = all[i][1], x2 = all[j][0], y2 = all[j][1];
  28. int len = (x1 - x2)*(x1 - x2) + (y1 - y2)*(y1 - y2);
  29. if (len == 0)
  30. return false;
  31. mmp[len]++;
  32. }
  33. }
  34. return mmp.size() == 2;
  35. }
  36. };

发表评论

表情:
评论列表 (有 0 条评论,255人围观)

还没有评论,来说两句吧...

相关阅读

    相关 593 有效正方形

    1. 问题描述: 给定二维空间中四点的坐标,返回四点是否可以构造一个正方形。一个点的坐标(x,y)由一个有两个整数的整数数组表示。 示例: 输入: p1 = \[0,0\