問題
原文
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:
12 Input: coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]]Output: trueExample 2:
12 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.
内容
座標の配列coordinatesが与えられます。coordinates[i]は[x,y]であり、x,y座標を意味します。各点が直線状に並んでいるか確かめてください。
制約
・coordinatesの長さは2~1000
・coordinates[i]にの長さは2
・x,yは、-10^4~10^4の範囲内
・coordinatesは同じ点を持たない
※正しくない可能性があります。
方針
・直線状に並んでいる場合は、2点間の傾きは一致するので、各点に対して確かめる
解答
解答1:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#(y-y1)/(y2-y1) = (x-x1)/(x2-x1) → (y-y1)*(x2-x1) = (x-x1)*(y2-y1) class Solution: def checkStraightLine(self, coordinates: List[List[int]]) -> bool: #1つ目の点を保持 x1,y1 = coordinates[0] #2つ目の点を保持 x2,y2 = coordinates[1] #3つ目の点から最後の点まで処理 for i in range(2,len(coordinates)): #i番目の点を保持 x, y = coordinates[i] #i番目の点と1,2番目の点の座標を使って直線状に並んでいるか確認。 if (y-y1)*(x2-x1) != (x-x1)*(y2-y1): return False #最後の点まで直線状に並んでいたならTrueを返す return True |
解答2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
class Solution: def checkStraightLine(self, coordinates: List[List[int]]) -> bool: slope = 0 for i in range(len(coordinates)-1): x1,y1 = coordinates[i] x2,y2 = coordinates[i+1] if x2-x1==0: m = float('inf') else: m=(y2-y1)/(x2-x1) if slope==0: slope=m else: if slope!=m: return False return True |
補足・参考・感想
参考
前:1290. Convert Binary Number in a Linked List to Integer
次:
コメント