Leetcode題解 Python & C#:五月挑戰DAY8 Check If It Is a Straight Line

檢查是否所有座標都在一條直線上。
這是很簡單的數學題,只要細節不漏掉就好。
寫出方程式: ax + b = y。但這不適用於垂直直線,因為同 x 會出現兩個以上的 y。 
這兩種情況要分開判斷,只要不是垂直直線的,靠解方程式就可以判斷。
若是,則看所有的座標的x是否為相同值。
(打完題解後,發現我本來寫好的是錯的但卻可以接受,只好幫提供testcase,默默改正code。

Python
class Solution:
def checkStraightLine(self, coordinates: List[List[int]]) -> bool:
dx = coordinates[1][0] - coordinates[0][0]
if dx == 0:
x = coordinates[0][0]
return all(map(lambda c: c[0] == x, coordinates))
else:
a = (coordinates[1][1] - coordinates[0][1]) / dx
b = coordinates[0][1] - a*coordinates[0][0]
return all(map(lambda c: a*c[0] == c[1]-b, coordinates))

C#

public class Solution {
public bool CheckStraightLine(int[][] coordinates) {
int dx = coordinates[1][0] - coordinates[0][0];
if(dx == 0)
{
int x = coordinates[0][0];
foreach(var c in coordinates)
{
if(c[0] != x)
{
return false;
}
}
}
else
{
double a = (coordinates[1][1] - coordinates[0][1]) / dx;
double b = coordinates[0][1] - a * coordinates[0][0];
foreach(var c in coordinates)
{
if(c[0]*a != c[1]-b)
{
return false;
}
}
}
return true;
}
}