首页 > 其他 > 详细

Leetcode 593: Valid Square

时间:2017-12-30 10:42:19      阅读:371      评论:0      收藏: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:

  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

原文:https://www.cnblogs.com/liangmou/p/8148649.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!