This is the 20th day of my participation in the August Text Challenge.More challenges in August

describe

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: trueCopy the code

Example 2:

Input: coordinates = [[1, 1], [2], [3, 4], [4, 5], [5, 6], [7, 7]] Output: falseCopy the code

Note:

2 <= coordinates.length <= 1000
coordinates[i].length == 2
-10^4 <= coordinates[i][0], coordinates[i][1] <= 10^4
coordinates contains no duplicate point.
Copy the code

parsing

Coordinates returns True if only two points are on a straight line, because the coordinates must be on a straight line.

If there are multiple points, calculate the slope p of the line formed by the first two points, and then iterate from the third point to determine whether it is the same as the slope p of the line formed by the second point. If not, return False.

It then checks whether the slope of the line formed by the fourth and third points is the same as p, and returns False if they are not, and so on, True if they are all on the same line at the end of the walk.

When you calculate the slope, the slope is 0 when y is the same at both points, and the slope is a large number when x is the same at both points. Otherwise, you just calculate the slope. In addition, abs(A-b) > 0.0001 is needed to determine whether decimals are equal.

answer

class Solution(object):
    def checkStraightLine(self, coordinates):
        """
        :type coordinates: List[List[int]]
        :rtype: bool
        """
        if len(coordinates)==2:
            return True
        def cal_slope(p1, p2):
            x, y = p1[0], p1[1]
            x_, y_ = p2[0], p2[1]
            deltay = y_ - y
            deltax = x_ - x
            if deltax == 0:
                return float("inf")
            elif deltay == 0:
                return 0
            else:
                return deltay/deltax
        p = cal_slope(coordinates[0], coordinates[1])
        for i in range(2,len(coordinates)):
            tmp = cal_slope(coordinates[i-1], coordinates[i])
            if abs(tmp- p) > 0.0001:
                return False
        return True
        	      
		
Copy the code

The results

The given node in the linked list Is linked to the node in the linked list. The submissions in the Python online submissions list for Check If It Is a Straight Line.Copy the code

Original link: leetcode.com/problems/ch…

Your support is my biggest motivation