1. 程式人生 > 實用技巧 >1232. Check If It Is a Straight Line

1232. Check If It Is a Straight Line

問題:

給定一組座標點,問這些座標點是否在一條直線上。

Example 1:
Input: coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]]
Output: true

Example 2:
Input: coordinates = [[1,1],[2,2],[3,4],[4,5],[5,6],[7,7]]
Output: false
 
Constraints:
2 <= coordinates.length <= 1000
coordinates[i].length == 2
-10^4 <= coordinates[i][0], coordinates[i][1] <= 10^4
coordinates contains no duplicate point.

解法:

任意兩點之間點斜率slope(k)相等。

double slope=(y1-y2)/(x1-x2)

⚠️ 注意:

特殊的兩條線,平行於x軸,y軸的兩種線

平行於x軸的斜率為0,

平行於y軸的斜率為∞,這裡假設為INT_MAX

程式碼參考:

 1 class Solution {
 2 public:
 3     bool checkStraightLine(vector<vector<int>>& coordinates) {
 4         int N=coordinates.size();
 5         if
(N==2) return true; 6 double k=(coordinates[1][0]-coordinates[0][0]==0)?INT_MAX:(coordinates[1][1]-coordinates[0][1])*1.0/(coordinates[1][0]-coordinates[0][0]); 7 for(int i=2; i<N; i++){ 8 double k1=(coordinates[i][0]-coordinates[i-1][0]==0)?INT_MAX:(coordinates[i][1]-coordinates[i-1
][1])*1.0/(coordinates[i][0]-coordinates[i-1][0]); 9 if(k1!=k) return false; 10 } 11 return true; 12 } 13 };