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: 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.

看完题目,回家想了一路,大概思路是求两点之间的距离,如果是正方形两点之前的距离只有个值,暴力破解两层循环,代码不堪入目

看评论区有个两行搞定的

class Solution(object):
    def validSquare(self, p1, p2, p3, p4):
        """
        :type p1: List[int]
        :type p2: List[int]
        :type p3: List[int]
        :type p4: List[int]
        :rtype: bool
        """
        points = [p1, p2, p3, p4]
        return len({(a[0]-b[0])**2 + (a[1]-b[1])**2 for a in points for b in points}) == 3 and \
               len(set(map(tuple, points))) == 4
复制代码

看完惊了个呆,这是什么骚操作,集合推导式套两层for循环,查了下资料发现

{(a[0]-b[0])**2 + (a[1]-b[1])**2 for a in points for b in points}
#相当与
for a in points:
    for b in points:
        a[0]-b[0])**2 + (a[1]-b[1])**2
#然后集合去重
len(set(map(tuple, points)))
#这句的意思是看有没有重复的点
复制代码

代码的大概意思也是求两点间的距离,不过包含自己到自己,所以有三个值

涨姿势了,不过话说回来这也是暴力破解,回头再找找时间复杂度好点的

转载于:https://juejin.im/post/5c76cefe5188251961019441

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值