LeetCode 1232. Check If It Is a Straight Line

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
bool checkStraightLine(vector<vector<int>>& coordinates) {
const int n = coordinates.size();
if (n == 2) return true;
if (coordinates[1][0] == coordinates[0][0]) {
int x = coordinates[0][0];
for (int i = 2; i < n; ++i)
if (coordinates[i][0] != x)
return false;
} else {
double k = (coordinates[1][1] - coordinates[0][1]) / (1.0 * coordinates[1][0] - coordinates[0][0]);
double b = coordinates[0][1] - k * coordinates[0][0];
for (int i = 2; i < n; ++i)
if ((k * coordinates[i][0] + b) != coordinates[i][1])
return false;
}
return true;
}
};