码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 593: Valid Square

时间:2017-12-30 12:30:04      阅读:105      评论:0      收藏:0      [点我收藏+]

标签:++   key   dict   ons   solution   var   represent   color   each   

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

标签:++   key   dict   ons   solution   var   represent   color   each   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!