文章目录
- 一、题目
- 二、题解
一、题目
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.
二、题解
class Solution {
public:bool checkStraightLine(vector<vector<int>>& coordinates) {int n = coordinates.size();double x1 = coordinates[0][0],x2 = coordinates[1][0];double y1 = coordinates[0][1],y2 = coordinates[1][1];if(x1 - x2 == 0){for(int i = 2;i < n;i++){if(coordinates[i][0] != x1) return false;}return true;}double k = (y2 - y1) / (x2 - x1);double b = y1 - k * x1;for(int i = 2;i < n;i++){double xi = coordinates[i][0],yi = coordinates[i][1];if(yi != k * xi + b) return false;}return true;}
};