leetcode 593. Valid Square练习

Given the coordinates of four points in 2D space, return whether the four points could construct a square.bash

The coordinate (x,y) of a point is represented by an integer array with two integers.ide

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

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

看评论区有个两行搞定的code

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循环,查了下资料发现input

{(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)))
#这句的意思是看有没有重复的点
复制代码

代码的大概意思也是求两点间的距离,不过包含本身到本身,因此有三个值string

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

相关文章
相关标签/搜索