leetcode 593. Valid Square練習

笨小孩發表於2019-02-27

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)))
#這句的意思是看有沒有重複的點
複製程式碼

程式碼的大概意思也是求兩點間的距離,不過包含自己到自己,所以有三個值

漲姿勢了,不過話說回來這也是暴力破解,回頭再找找時間複雜度好點的

相關文章