【leetcode】1232. Check If It Is a Straight Line


題目如下:

You are given an array coordinatescoordinates[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.

解題思路:初中幾何知識,任意取兩個點,解出方程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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM