leetcode 1232. Check If It Is a Straight Line

文章目录

      • 159 场周赛第一题
      • 题意
      • 思路
        • python


Easy

159 场周赛第一题

题意

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: 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.

思路

这道题很简单,就是看所有的点之间的斜率是否相等就行。结果一开始没想到这个,走了很多误区,结果半小时才AC,真是菜!?

python

class Solution:
    def checkStraightLine(self, coordinates: List[List[int]]) -> bool:
        k = []
        for i in range(1,len(coordinates)):
            count=1
            dy= (coordinates[i][1]-coordinates[i-1][1])
            dx=(coordinates[i][0]-coordinates[i-1][0])
            if dx==0:
                count=0
            else:count=dy/dx
            k.append(count)
        k=set(k)
        if len(k)==1:
            return True
        else:return False

你可能感兴趣的:(leetcode解题之旅,算法,leetcode)