1232. 綴點成線
阿新 • • 發佈:2021-01-18
技術標籤:演算法
題目描述
在一個 XY 座標系中有一些點,我們用陣列 coordinates 來分別記錄它們的座標,其中 coordinates[i] = [x, y] 表示橫座標為 x、縱座標為 y 的點。
請你來判斷,這些點是否在該座標系中屬於同一條直線上,是則返回 true,否則請返回 false。
題解
轉載自力扣以及大佬描述
解法一:
直線一般式 Ax+By+c=0,即將所有座標一致移動,使所成直線穿過原點(0,0)。思考時總想著第三個未知數c是比較麻煩的,所以此法去掉一個未知數c。(我真的覺得喵喵喵!找到做數學題的感覺了,畢竟是聽帥氣哥說的,傳了再傳嘻嘻,廢話廢話,請略過)
class Solution {
public boolean checkStraightLine(int[][] coordinates) {
int deltaX = coordinates[0][0], deltaY = coordinates[0][1];
int n = coordinates.length;
for (int i = 0; i < n; i++) {
coordinates[i][0] -= deltaX;
coordinates[i][1] -= deltaY;
}
int A = coordinates[1][1], B = -coordinates[1][0];
for (int i = 2; i < n; i++) {
int x = coordinates[i][0], y = coordinates[i][1];
if (A * x + B * y != 0) {
return false;
}
}
return true;
}
}
/*
作者:LeetCode-Solution
連結:https://leetcode-cn.com/problems/check-if-it-is-a-straight-line/solution/zhui-dian-cheng-xian-by-leetcode-solutio-lpt6/
來源:力扣(LeetCode)
著作權歸作者所有。商業轉載請聯絡作者獲得授權,非商業轉載請註明出處。*/
解法二:
兩點式解法
兩點式:(y-y1)/(x-x1)=(y-y2)/(x-x2) (直線過定點(x1,y1),(x2,y2))
取定點為coordinates[0],和coordinates[n-1],為避免除法運算,這裡用“兩內項的積等於兩外項的積”計算
class Solution {
public:
bool checkStraightLine(vector<vector<int>>& coordinates) {
/*
* 一般式:Ax+By+C=0(AB≠0)
* 兩點式:(y-y1)/(x-x1)=(y-y2)/(x-x2) (直線過定點(x1,y1),(x2,y2))
*/
// 這裡取定點為coordinates[0],和coordinates[n-1]
// 為避免除法運算,這裡用“兩內項的積等於兩外項的積”計算
int n = coordinates.size();
for(int i = 1; i < coordinates.size()-1; ++i)
{
if(
(coordinates[i][0] - coordinates[0][0])* /* (x-x1)*(y-y2) */
(coordinates[i][1] - coordinates[n-1][1])
!=
(coordinates[i][1] - coordinates[0][1])* /* (y-y1)*(x-x2) */
(coordinates[i][0] - coordinates[n-1][0])
) return false;
}
return true;
}
};
//轉載自力扣官方解答下面評論,大佬厲害
第二種方法源主