Try   HackMD

【LeetCode】 1232. Check If It Is a Straight Line

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.

Constraints:

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

給你一個陣列coordinates,且coordinates[i] = [x, y],其中[x, y]代表一個點座標。檢查這些點是否在XY平面上形成一條直線。

限制:

  • 2 <= coordinates.length <= 1000
  • coordinates[i].length == 2
  • -10^4 <= coordinates[i][0], coordinates[i][1] <= 10^4
  • coordinates 不會有重複的點。

Example:

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


Solution

  • 檢查斜率是否一致即可(Y的變化量 / X的變化量)。
    • 我下面的code不小心把X和Y用反,但其實沒差。
  • 然後要注意分母為零的情況,改為確認分母都是一樣的值即可。

Code

class Solution { public: bool checkStraightLine(vector<vector<int>>& coordinates) { if(coordinates[0][1] - coordinates[1][1] == 0) { for(int i = 2; i < coordinates.size(); i++) { if((coordinates[0][1] - coordinates[i][1]) != 0) return false; } return true; } double radio = (double)(coordinates[0][0] - coordinates[1][0]) / (coordinates[0][1] - coordinates[1][1]); cout << radio; for(int i = 2; i < coordinates.size(); i++) { if((double)(coordinates[0][0] - coordinates[i][0]) / (coordinates[0][1] - coordinates[i][1]) != radio) return false; } return true; } };
tags: LeetCode C++