Easy
,Array
,Math
1232. Check If It Is a Straight Line
You are given an array coordinates
, coordinates[i]
= [x, y]
, where [x, y]
represents the coordinate of a point. Check if these points make a straight line in the XY plane.
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:
coordinates.length
<= 1000coordinates[i].length
== 2coordinates[i][0]
, coordinates[i][1]
<= 104coordinates
contains no duplicate point.
class Solution:
def checkStraightLine(self, coordinates: List[List[int]]) -> bool:
if len(coordinates) == 2:
return True
x0, y0 = coordinates[0]
x1, y1 = coordinates[1]
dx, dy = x1 - x0, y1 - y0
for i in range(2, len(coordinates)):
x, y = coordinates[i]
if (x - x0) * dy != (y - y0) * dx:
return False
return True
Yen-Chi ChenMon, Jun 5, 2023
class Solution {
public:
bool checkStraightLine(vector<vector<int>>& coordinates) {
int n = coordinates.size();
if (n == 2) {
return true;
}
const auto st = coordinates[0];
int xDiff = (st[0] - coordinates[1][0]);
int yDiff = (st[1] - coordinates[1][1]);
for (int i = 2; i < coordinates.size(); i ++) {
const auto u = coordinates[i];
if (xDiff * (st[1] - u[1]) != yDiff * (st[0] - u[0])) {
return false;
}
}
return true;
}
};
Jerry Wu5 June, 2023
class Solution {
public boolean checkStraightLine(int[][] coordinates) {
int x0 = coordinates[0][0], y0 = coordinates[0][1],
x1 = coordinates[1][0], y1 = coordinates[1][1];
int dx = (x1 - x0), dy = (y1 - y0);
for(int[] coordinate : coordinates) {
int x = coordinate[0];
int y = coordinate[1];
if(dx * (y - y1) != dy * (x - x1))
return false;
}
return true;
}
}
Ron ChenMon, June5, 2023
public bool CheckStraightLine(int[][] coordinates) {
if (coordinates.Length == 2) return true;
int x1 = coordinates[1][0] - coordinates[0][0];
int y1 = coordinates[1][1] - coordinates[0][1];
for (int n = 2; n < coordinates.Length; n++) {
int xn = coordinates[n][0] - coordinates[0][0];
int yn = coordinates[n][1] - coordinates[0][1];
if (x1 * yn != y1 * xn){
return false;
}
}
return true;
}
JimJun 5, 2023
function checkStraightLine(coordinates) {
const [x1, y1] = coordinates[0];
const [x2, y2] = coordinates[1];
for (let i = 2; i < coordinates.length; i++) {
const [x, y] = coordinates[i];
if ((y2 - y1) * (x - x1) !== (y - y1) * (x2 - x1)) return false;
}
return true;
}
MarsgoatJun 5, 2023