Leetcode 593: Valid Square

Posted Keep walking

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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:

  1. All the input integers are in the range [-10000, 10000].
  2. A valid square has four equal sides with positive length and four equal angles (90-degree angles).
  3. Input points have no order.
 1 public class Solution {
 2     public bool ValidSquare(int[] p1, int[] p2, int[] p3, int[] p4) {
 3         var dict = new Dictionary<int, int>();
 4         var list = new List<int>(6);
 5         
 6         list.Add(GetLengthSquare(p1, p2));
 7         list.Add(GetLengthSquare(p1, p3));
 8         list.Add(GetLengthSquare(p1, p4));
 9         list.Add(GetLengthSquare(p2, p3));
10         list.Add(GetLengthSquare(p2, p4));
11         list.Add(GetLengthSquare(p3, p4));
12         
13         foreach (var l in list)
14         {
15             if (!dict.ContainsKey(l))
16             {
17                 dict[l] = 1;
18             }
19             else
20             {
21                 dict[l]++;
22             }
23         }
24         
25         if (dict.Count != 2) return false;
26         
27         foreach (var pair in dict)
28         {
29             if (pair.Value != 2 && pair.Value != 4)
30             {
31                 return false;
32             }
33         }
34         
35         return true;
36     }
37     
38     private int GetLengthSquare(int[] p1, int[] p2)
39     {
40         return (int)Math.Pow((p2[0] - p1[0]), 2) + (int)Math.Pow((p2[1] - p1[1]), 2);
41     }
42 }

 

以上是关于Leetcode 593: Valid Square的主要内容,如果未能解决你的问题,请参考以下文章

leetcode No593. Valid Square

leetcode No593. Valid Square

LC 593. Valid Square

LeetCode 0593. 有效的正方形

Leetcode 593.???????????????

C#刷遍Leetcode面试题系列连载:No.593 - 有效的正方形