【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: trueExample 2:
Input: coordinates = [[1,1],[2,2],[3,4],[4,5],[5,6],[7,7]] Output: falseConstraints:
2 <= coordinates.length <= 1000
coordinates[i].length == 2
-10^4 <= coordinates[i][0], coordinates[i][1] <= 10^4
coordinates
contains no duplicate point.
解题思路:初中几何知识,任意取两个点,解出方程y = k*x + b,然后判断其余点是否满足方程。
代码如下:
class Solution(object): def checkStraightLine(self, coordinates): """ :type coordinates: List[List[int]] :rtype: bool """ x1,y1 = coordinates[0] x2,y2 = coordinates[1] k_numerator = (y1-y2) k_denominator = (x1-x2) if k_denominator == 0: k_denominator = 1 b = y1 - k_numerator/k_denominator*x1 for i in range(2,len(coordinates)): x,y = coordinates[i] if y != k_numerator/k_denominator*x + b: return False return True
标签:point,Straight,denominator,numerator,coordinates,y1,Line,x1,leetcode 来源: https://www.cnblogs.com/seyjs/p/11713607.html