Leetcode 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
Description
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:
2 <= coordinates.length <= 1000
coordinates[i].length == 2
-10^4 <= coordinates[i][0], coordinates[i][1] <= 10^4
coordinates
contains no duplicate point.
Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
from typing import List
class Solution:
# Iteration
# Time Complexity: BigO(N)
# Space Complexity: BigO(1)
def checkStraightLine(self, coordinates: List[List[int]]) -> bool:
mxd = coordinates[1][0] - coordinates[0][0]
myd = coordinates[1][1] - coordinates[0][1]
for i in range(1, len(coordinates) - 1):
nxd = coordinates[i + 1][0] - coordinates[i][0]
nyd = coordinates[i + 1][1] - coordinates[i][1]
if mxd > nxd and myd > nyd:
try:
ckx = mxd / nxd
cky = myd / nyd
if ckx == cky:
mxd = nxd
myd = nyd
continue
except ZeroDivisionError:
return False
return False
elif (mxd == 0 and nxd == 0) or (myd == 0 and nyd == 0):
continue
else:
try:
ckx = mxd / nxd
cky = myd / nyd
if ckx == cky:
continue
except ZeroDivisionError:
return False
return False
return True
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/**
* Iteration
* Time Complexity: BigO(N)
* Space Complexity: BigO(1)
*/
function checkStraightLine(coordinates: number[][]): boolean {
let mxd = coordinates[1][0] - coordinates[0][0];
let myd = coordinates[1][1] - coordinates[0][1];
for (let i = 1; i < coordinates.length - 1; i++) {
let nxd = coordinates[i + 1][0] - coordinates[i][0];
let nyd = coordinates[i + 1][1] - coordinates[i][1];
if (mxd > nxd && myd > nyd) {
let ckX = mxd / nxd;
let ckY = myd / nyd;
if (ckX == ckY) {
mxd = nxd;
myd = nyd;
continue;
}
return false;
} else if ((mxd == 0 && nxd == 0) || (myd == 0 && nyd == 0)) {
continue;
} else {
let ckX = nxd / mxd;
let ckY = nyd / myd;
if (ckX == ckY) {
continue;
}
return false;
}
}
return true;
}
This post is licensed under CC BY 4.0 by the author.