1232.缀点成线(Java)

题目描述:

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

输入:

coordinates = \[1,2,2,3,3,4,4,5,5,6,6,7]

输出:

true

代码实现:

java 复制代码
//缀点成线
public class Main{
    public static void main(String[] args) {
        int[][] coordinates = new int[][]{{1, 2}, {2, 3}, {3, 4}, {4, 5}, {5, 6}, {6, 7}};
        System.out.println(checkStraightLine(coordinates));//true
    }

    public static boolean checkStraightLine(int[][] coordinates) {
        //设:A*X + B*Y = 0;
        //将方程平移过零点
        for (int i = 1; i < coordinates.length; i++) {
            coordinates[i][0] -= coordinates[0][0];
            coordinates[i][1] -= coordinates[0][1];
        }
        //归零
        coordinates[0][0] = 0;
        coordinates[0][1] = 0;
        //计算参数
        int a = coordinates[1][1];
        int b = -coordinates[1][0];
        //判断剩下的点是否在该直线上
        for (int i = 2; i < coordinates.length; i++) {
            int[] temp = coordinates[i];//点
            int x = temp[0];//横坐标
            int y = temp[1];//纵坐标
            if (a * x + b * y != 0) {
                //如果有任意一点不满足方程:则返回结果假
                return false;
            }
        }
        //循环结束之后,则表示都满足方程:则返回真
        return true;
    }
}
相关推荐
渡我白衣15 分钟前
深入理解 Transformer:Transformer 究竟是什么?
java·linux·开发语言·c++·人工智能·深度学习·transformer
Tisfy3 小时前
LeetCode 1927.求和游戏:抵消+看最值
java·leetcode·游戏·题解·博弈论
「QT(C++)开发工程师」8 小时前
C++ 11 常用for循环
开发语言·c++
我还记得那天8 小时前
0 初识C++
开发语言·c++
FfHUCisI9 小时前
Go 编译过程全景
开发语言·后端·golang
FfHUCisI9 小时前
Golang 语法分析与 AST:Parser 与 go/ast
开发语言·后端·golang
秋饼9 小时前
JDK 27 企业级 AI 服务落地实战:G1 默认、紧凑对象头、后量子 TLS 与 JFR 脱敏全解析
java·ai·技术分享·后端开发
卓怡学长10 小时前
w176基于SpringBoot的医院管理系统
java·spring boot·spring·maven·intellij-idea
lemon_sjdk10 小时前
ObjectProperty
java·开发语言·算法