Valid Square
来源:互联网 发布:北京资采数据挖掘 编辑:程序博客网 时间:2024/05/16 04:47
题目描述:
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)存在四个边段距离相等 2)存在两个对角线距离相等。则构成四边形。
注意:在求点距离的时候需要注意是否存在整数溢出,由于给定范围是[-10000,10000],最大值不会超过2^32 -1,因此不用担心
代码:
class Solution { public boolean validSquare(int[] p1, int[] p2, int[] p3, int[] p4) { int[] d = new int[6]; d[0] = distance(p1, p2); d[1] = distance(p1, p3); d[2] = distance(p1, p4); d[3] = distance(p2, p3); d[4] = distance(p2, p4); d[5] = distance(p3, p4); Arrays.sort(d); return d[0] == d[3] && d[3]<d[4] && d[4] == d[5]; } private int distance(int[] p1, int[] p2) { int x = Math.abs(p1[0] - p2[0]); int y = Math.abs(p1[1] - p2[1]); return x * x + y * y; }}
阅读全文
0 0
- Valid Square
- Valid Square
- 141.Valid Perfect Square
- 367. Valid Perfect Square
- LeetCode:Valid Perfect Square
- 【Leetcode】valid perfect square
- [leetcode] Valid Perfect Square
- 367. Valid Perfect Square
- leetcode367. Valid Perfect Square
- 367. Valid Perfect Square
- 367. Valid Perfect Square
- 367. Valid Perfect Square
- Valid Perfect Square
- leetcode---Valid Perfect Square
- 367. Valid Perfect Square
- Valid Perfect Square
- Valid Perfect Square
- 367. Valid Perfect Square
- 【Linux】linux性能分析工具oprofile移植
- This application failed to start because it could not find or load the Qt platform plugin “windows”错
- 2017年首份中美数据科学对比报告,Python受欢迎度排名第一,美国数据工作者年薪中位数高达11万美金
- JMAP的使用
- 利用RNN训练Seq2Seq已经成为过去,CNN才是未来?
- Valid Square
- 五年之后,你的企业是拥抱AI,还是已被淘汰
- gcc链接静态库成功但是g++失败
- The content of element type "tag" must match
- android+mvp基本
- idaa常用快捷键
- Spring Boot 快速入门
- PHP的AOP编程详解
- 波士顿美联储高级副总裁:分布式账本可能“从根本上改变”金融业