[Leetcode] 1232. Check If It Is a Straight Line (Easy)

概述

題目

https://leetcode.com/problems/check-if-it-is-a-straight-line/
給予數個點,確認此些點是否都在同一直線上

心得

應該也是滿直覺的數學題,透過平面座標求兩點求直線,再看餘下點是否都經過此線即可,唯一需注意除數為 0 的狀況

Math

思路

取兩點求直線,餘下點帶入後等式成立則同直線、否則非直線

程式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution(object):
def checkStraightLine(self, coordinates):
"""
:type coordinates: List[List[int]]
:rtype: bool
"""
n = len(coordinates)
if n < 3:
return True

x0, y0 = coordinates[0]
x1, y1 = coordinates[1]

# 先確認水平線之狀況
if y1 == y0:
for i in range(n):
x, y = coordinates[i]
if y != y0:
return False

# 餘下的情況
else:
for i in range(2, n):
x, y = coordinates[i]
if y-y0 != 0:
if (x1-x0)/(y1-y0) != (x-x0)/(y-y0):
return False
else:
return False
return True

除數有可能是零的狀況,則轉換 a/b vs c/d => a*d vs c*b

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution(object):
def checkStraightLine(self, coordinates):
"""
:type coordinates: List[List[int]]
:rtype: bool
"""
n = len(coordinates)
if n < 3:
return True

x0, y0 = coordinates[0]
x1, y1 = coordinates[1]

dx = x1-x0
dy = y1-y0

for x, y in coordinates:
if dx * (y-y1) != dy * (x-x1):
return False
return True

Complexity

Time Complexity: O(n)
共有 n 個點,操作 n 次,故 O(n)

Space Complexity: O(1)
基本上無使用到額外空間