LeetCode 593. Valid Square 平面四点能否正方形

231 篇文章 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.

---------------------------------------

只考虑边长的关系,这题的写法就简化了一半,如果涉及到斜率写起来比较烦。。。

既然只考虑边长,那么会有两种思路:

思路一:枚举6个定点中两两点之间的长度,正方形最后只有2种长度,同时不包含为0的长度。证明可以从挑两两相等的边去考虑。

class Solution:
    def validSquare(self, p1,p2,p3,p4) -> bool:
        def dis(x,y):
            xdis,ydis=x[0]-y[0],x[1]-y[1]
            return xdis*xdis+ydis*ydis
        d12,d13,d14,d23,d24,d34=dis(p1,p2),dis(p1,p3),dis(p1,p4),dis(p2,p3),dis(p2,p4),dis(p3,p4)
        dset = {d12,d13,d14,d23,d24,d34}
        return len(dset) == 2 and 0 not in dset

思路二:把4个点按横坐标、纵坐标排序,发现正方形排序后只有两种情况,那么判断这两种情况就可以:

class Solution:
    def validSquare(self, p1,p2,p3,p4) -> bool:
        def dis(x,y):
            xdis,ydis=x[0]-y[0],x[1]-y[1]
            return xdis*xdis+ydis*ydis
        pp = sorted([p1,p2,p3,p4])
        d01,d13,d23,d02,d12,d03=dis(pp[0],pp[1]),dis(pp[1],pp[3]),dis(pp[2],pp[3]),dis(pp[0],pp[2]),dis(pp[1],pp[2]),dis(pp[0],pp[3])
        return d01>0 and d01==d13 and d13==d23 and d23==d02 and d12==d03

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值