綴點成線
問題:
在一個 XY 坐標系中有一些點,我們用陣列 coordinates 來分別記錄它們的坐標,其中coordinates[i] = [x, y]表示橫坐標為 x、縱坐標為 y 的點,
行數 = 2;
請你來判斷,這些點是否在該坐標系中屬于同一條直線上,是則回傳 true,否則請回傳 false,
思路:
將所有點平移第一個點的位置大小,那么這些點如果在一條直線上,其他所有點都應該滿足 A * x + B * y = 0
不滿足回傳 false ,全部滿足回傳 true,
class Solution {
public:
bool checkStraightLine(vector<vector<int>>& coordinates) {
const int n = coordinates.size(); // 列數
auto deltX = coordinates[0][0], deltY = coordinates[0][1];
for(int i = 0; i < n; ++i){
coordinates[i][0] -= deltX;
coordinates[i][1] -= deltY;
}
auto A = coordinates[1][1], B = -coordinates[1][0];
for(int j = 2; j < n; ++j){
if(A * coordinates[j][0] + B * coordinates[j][1] != 0)
return false;
}
return true;
}
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/250141.html
標籤:其他
