--- title: 1232. Check If It Is a Straight Line tags: leetcode,解題報告 --- {%hackmd @hlc23/dark-theme %} # 1232. Check If It Is a Straight Line 題目連結: [Leetcode](https://leetcode.com/problems/check-if-it-is-a-straight-line/description/) ## 題目概要 給一連串的座標 檢查是否在同一直線上 ## 想法 ### 作法一 檢查斜率 一直線的斜率為$\frac{\Delta x}{\Delta y}$ 因此只要檢查每一點跟第一點所形成的直線的斜率是否相同 $$\frac{\Delta x_1}{\Delta y_1} = \frac{\Delta x_2}{\Delta y_2}$$ 這個作法有個要注意的點是$\Delta y = 0$ 也就是鉛直線 鉛直線的斜率為不存在會導致分母為0造成錯誤 因此分成兩個情況做計算 - 鉛直線: 判斷所有點的 $y$ 座標是否相同 - 非鉛直線: 計算斜率 ### 作法二 等式判斷 因為作法一要分成兩種情況太過麻煩 所以可以做等式移項避免做除法計算 $$\frac{\Delta x_1}{\Delta y_1} = \frac{\Delta x_2}{\Delta y_2} \\ \quad \\ \Delta x1 \times \Delta y_2 = \Delta x_2 \times \Delta y_1 $$ 移項後就不需要考慮鉛直線斜率不存在的問題 ## 參考解法 歡迎補充 :::spoiler CPP 法一 ```cpp= class Solution { public: bool checkStraightLine(vector<vector<int>>& coordinates) { int n = coordinates.size(); float x0 = coordinates[0][0], y0 = coordinates[0][1], x1 = coordinates[1][0], y1 = coordinates[1][1]; if (y0 == y1){ for (int i=1; i<n; i++){ if (coordinates[i][1] != y0) return false; } } else{ float slope = (x1 - x0) / (y1 - y0); for (int i=1; i<n; i++){ if ((coordinates[i][0] - x0) / (coordinates[i][1] - y0) != slope) return false; } } return true; } }; ``` ::: :::spoiler PY 法二 ```python= class Solution: def checkStraightLine(self, coordinates: List[List[int]]) -> bool: x0, y0 = coordinates[0][0], coordinates[0][1] x1, y1 = coordinates[1][0], coordinates[1][1] dx = x1 - x0 dy = y1 - y0 for xn, yn in coordinates: if (xn - x0) * dy != dx * (yn - y0): return False return True ``` :::