개발/Leetcode
Leetcode 1232. Check If It Is a Straight Line
지산동고라니
2023. 6. 24. 11:46
https://leetcode.com/problems/check-if-it-is-a-straight-line/description/
Check If It Is a Straight Line - LeetCode
Can you solve this real interview question? 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.
leetcode.com
문제
좌표의 정보가 들어있는 coordinates 배열이 주어진다. 배열의 각 원소에는 x, y 좌표에 대응하는 [x, y]의 정보가 들어있다. 배열에 주어진 점들이 모두 직선에 위치하는지 파악하여 위치한다면 True 그렇지 않으면 False를 반환하라
코드
class Solution:
def checkStraightLine(self, coordinates: list[list[int]]) -> bool:
delta_x = (coordinates[-1][0] - coordinates[0][0])
delta_y = (coordinates[-1][1] - coordinates[0][1])
if delta_x == 0:
return True if all(map(lambda x: x[0] == coordinates[0][0], coordinates)) else False
incle = delta_y / delta_x
y = coordinates[0][1] - coordinates[0][0] * incle
print(incle, y)
for coordinate in coordinates:
if coordinate[1] != y + coordinate[0] * incle:
return False
return True
x의 증가값과 y의 증가값을 바탕으로 기울기와 y 절편을 구해 각 점에 대해 기울기와 y절편에 대응하는 직선에 위치하는가에 대해 구현한 코드이다.
중간에 delta_x == 0을 비교한 코드는 직선이 수직선( y의 축에 일치하는) 경우는 delta_y가 0이므로 에러가 발생하는 문제를 해결하기 위해 추가한 코드이다.
난이도는 easy였지만 조금 어려웠다 ..