JavaInterview JavaInterview
首页
指南
分类
标签
归档
  • CSDN (opens new window)
  • 文档集合 (opens new window)
  • 系统架构 (opens new window)
  • 微信号 (opens new window)
  • 公众号 (opens new window)

『Java面试+Java学习』
首页
指南
分类
标签
归档
  • CSDN (opens new window)
  • 文档集合 (opens new window)
  • 系统架构 (opens new window)
  • 微信号 (opens new window)
  • 公众号 (opens new window)
  • 指南
  • 简历

  • Java

  • 面试

  • 算法

  • algorithm
  • leetcode
JavaInterview.cn
2023-02-27
目录

缀点成线Java

文章发布较早,内容可能过时,阅读注意甄别。

# 题目

给定一个数组 coordinates ,其中 coordinates[i] = [x, y] , [x, y] 表示横坐标为 x、纵坐标为 y 的点。请你来判断,这些点是否在该坐标系中属于同一条直线上。

示例 1:

输入:coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]] 输出:true 示例 2:

输入:coordinates = [[1,1],[2,2],[3,4],[4,5],[5,6],[7,7]] 输出:false

提示:

  • 2 <= coordinates.length <= 1000
  • coordinates[i].length == 2
  • -10^4 <= coordinates[i][0], coordinates[i][1] <= 10^4
  • coordinates 中不含重复的点

# 思路

// 线性回归是吧,判断有没有这样一个方程f(x)=kx+b,使得所有点都在线上

// 注意直线与y轴平行的情况

# 解法


class Solution {
    // 线性回归是吧,判断有没有这样一个方程f(x)=kx+b,使得所有点都在线上

    // 注意直线与y轴平行的情况
    public boolean checkStraightLine(int[][] coordinates) {
        int [] one=coordinates[0];
        int [] two=coordinates[1];
        double k=(one[0]==two[0])?(double)Integer.MAX_VALUE:(one[1]-two[1]-0.0)/(one[0]-two[0]);
        System.out.println(k);
        double b=one[1]-k*one[0];
        int n=coordinates.length;
        if(k==Integer.MAX_VALUE){
            int x=one[0];
            for(int i=0;i<n;i++){
                if(coordinates[i][0]!=x) return false;
            }
            return true;
        }
        for(int i=0;i<n;i++){
            int y=coordinates[i][1];
            int x=coordinates[i][0];
            if(y!=k*x+b) return false;
        }
        return true;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

# 总结

  • 分析出几种情况,然后分别对各个情况实现
微信 支付宝
最近更新
01
1686. 石子游戏VI Java
08-18
02
1688. 比赛中的配对次数 Java
08-18
03
1687. 从仓库到码头运输箱子 Java
08-18
更多文章>
Theme by Vdoing | Copyright © 2019-2025 JavaInterview.cn
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式