zoukankan      html  css  js  c++  java
  • 【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
  • 相关阅读:
    var 全局变量 局部变量
    C#的发展历程第五
    优雅的处理Redis访问超时
    《集体智慧编程》读书笔记10
    《集体智慧编程》读书笔记9
    C#码农的大数据之路
    C#码农的大数据之路
    C#码农的大数据之路
    C#码农的大数据之路
    .NET遇上Docker
  • 原文地址:https://www.cnblogs.com/seyjs/p/11713607.html
Copyright © 2011-2022 走看看