返回介绍

solution / 1200-1299 / 1232.Check If It Is a Straight Line / README_EN

发布于 2024-06-17 01:03:21 字数 3531 浏览 0 评论 0 收藏 0

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.

 

 

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.

Solutions

Solution 1: Mathematics

The time complexity is $O(n)$, where $n$ is the length of the coordinates array. The space complexity is $O(1)$.

class Solution:
  def checkStraightLine(self, coordinates: List[List[int]]) -> bool:
    x1, y1 = coordinates[0]
    x2, y2 = coordinates[1]
    for x, y in coordinates[2:]:
      if (x - x1) * (y2 - y1) != (y - y1) * (x2 - x1):
        return False
    return True
class Solution {
  public boolean checkStraightLine(int[][] coordinates) {
    int x1 = coordinates[0][0], y1 = coordinates[0][1];
    int x2 = coordinates[1][0], y2 = coordinates[1][1];
    for (int i = 2; i < coordinates.length; ++i) {
      int x = coordinates[i][0], y = coordinates[i][1];
      if ((x - x1) * (y2 - y1) != (y - y1) * (x2 - x1)) {
        return false;
      }
    }
    return true;
  }
}
class Solution {
public:
  bool checkStraightLine(vector<vector<int>>& coordinates) {
    int x1 = coordinates[0][0], y1 = coordinates[0][1];
    int x2 = coordinates[1][0], y2 = coordinates[1][1];
    for (int i = 2; i < coordinates.size(); ++i) {
      int x = coordinates[i][0], y = coordinates[i][1];
      if ((x - x1) * (y2 - y1) != (y - y1) * (x2 - x1)) {
        return false;
      }
    }
    return true;
  }
};
func checkStraightLine(coordinates [][]int) bool {
  x1, y1 := coordinates[0][0], coordinates[0][1]
  x2, y2 := coordinates[1][0], coordinates[1][1]
  for i := 2; i < len(coordinates); i++ {
    x, y := coordinates[i][0], coordinates[i][1]
    if (x-x1)*(y2-y1) != (y-y1)*(x2-x1) {
      return false
    }
  }
  return true
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文