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.
题目大意:二维平面给定任意数量(大于2)的点的坐标,判断这些点是不是位于同一条直线上。
这是一道十分简单的题目,有基本的数学基础的都可以做出来。选定一个基准点,然后依次遍历剩下的点,看看是不是斜率的绝对值都相同即可。为了更加方便地去计算,同时避免考虑斜率正负的问题,这里采用方向向量的方式进行计算。任意选择两个点,并选择其中的一个作为基准点,计算他们之间的方向向量。然后依次遍历剩下的点,计算基准点和其之间的方向向量,只要二者方向相同或相反就说明他们位于一条直线上。
Python代码如下:
class Solution:
def checkStraightLine(self, coordinates) -> bool:
if len(coordinates) <= 2:
return True
base = [coordinates[0][0] - coordinates[1][0], coordinates[0][1] - coordinates[1][1]]
for i in range(2, len(coordinates)):
v = [coordinates[0][0] - coordinates[i][0], coordinates[0][1] - coordinates[i][1]]
if v[0] * base[1] != v[0] * base[0]:
return False
return True
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: tru
Description
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]]
Problem
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.
Constraints:
2 <= coordinates.length <= 1000
coordinates[i].length ==
1232. Check If It Is a Straight Line*
https://leetcode.com/problems/check-if-it-is-a-straight-line/submissions/
检查一系列坐标点是否在同一直线上.
C++ 实现 1
看斜率是否一致. 使用乘法比较.
class Solution {
private:
bool isIn...
Problem
Given two strings text1 and text2, return the length of their longest common subsequence.
A subsequence of a string is a new string generated from the original string with some characters(can ...
Problem
You are driving a vehicle that has capacity empty seats initially available for passengers. The vehicle only drives east (ie. it cannot turn around and drive west.)
Given a list of trips, tri...
Problem
In an infinite binary tree where every node has two children, the nodes are labelled in row order.
In the odd numbered rows (ie., the first, third, fifth,…), the labelling is left to right, wh...
Problem
Given the root of a binary tree, the level of its root is 1, the level of its children is 2, and so on.
Return the smallest level X such that the sum of all the values of nodes at level X is m...