Try   HackMD

1232.Check If It Is a Straight Line

tags: Easy,Array,Math

1232. Check If It Is a Straight Line

題目描述

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:

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

Input: coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]]
Output: true

Example 2:

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

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
  • -104 <= coordinates[i][0], coordinates[i][1] <= 104
  • coordinates contains no duplicate point.

解答

Python

class Solution: def checkStraightLine(self, coordinates: List[List[int]]) -> bool: if len(coordinates) == 2: return True x0, y0 = coordinates[0] x1, y1 = coordinates[1] dx, dy = x1 - x0, y1 - y0 for i in range(2, len(coordinates)): x, y = coordinates[i] if (x - x0) * dy != (y - y0) * dx: return False return True

Yen-Chi ChenMon, Jun 5, 2023

C++

class Solution { public: bool checkStraightLine(vector<vector<int>>& coordinates) { int n = coordinates.size(); if (n == 2) { return true; } const auto st = coordinates[0]; int xDiff = (st[0] - coordinates[1][0]); int yDiff = (st[1] - coordinates[1][1]); for (int i = 2; i < coordinates.size(); i ++) { const auto u = coordinates[i]; if (xDiff * (st[1] - u[1]) != yDiff * (st[0] - u[0])) { return false; } } return true; } };

Jerry Wu5 June, 2023

Java

class Solution { public boolean checkStraightLine(int[][] coordinates) { int x0 = coordinates[0][0], y0 = coordinates[0][1], x1 = coordinates[1][0], y1 = coordinates[1][1]; int dx = (x1 - x0), dy = (y1 - y0); for(int[] coordinate : coordinates) { int x = coordinate[0]; int y = coordinate[1]; if(dx * (y - y1) != dy * (x - x1)) return false; } return true; } }

Ron ChenMon, June5, 2023

C#

public bool CheckStraightLine(int[][] coordinates) { if (coordinates.Length == 2) return true; int x1 = coordinates[1][0] - coordinates[0][0]; int y1 = coordinates[1][1] - coordinates[0][1]; for (int n = 2; n < coordinates.Length; n++) { int xn = coordinates[n][0] - coordinates[0][0]; int yn = coordinates[n][1] - coordinates[0][1]; if (x1 * yn != y1 * xn){ return false; } } return true; }

JimJun 5, 2023

Javascript

function checkStraightLine(coordinates) { const [x1, y1] = coordinates[0]; const [x2, y2] = coordinates[1]; for (let i = 2; i < coordinates.length; i++) { const [x, y] = coordinates[i]; if ((y2 - y1) * (x - x1) !== (y - y1) * (x2 - x1)) return false; } return true; }

MarsgoatJun 5, 2023

Reference

回到題目列表