1232.缀点成线(Java)

题目描述:

给定一个数组 coordinates ,其中 coordinates[i] = [x, y] , [x, 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;
    }
}
相关推荐
雨中飘荡的记忆10 小时前
ElasticJob分布式调度从入门到实战
java·后端
考虑考虑18 小时前
JDK25模块导入声明
java·后端·java ee
_小马快跑_19 小时前
Java 的 8 大基本数据类型:为何是不可或缺的设计?
java
Re_zero1 天前
线上日志被清空?这段仅10行的 IO 代码里竟然藏着3个毒瘤
java·后端
洋洋技术笔记1 天前
Spring Boot条件注解详解
java·spring boot
程序员清风2 天前
程序员兼职必看:靠谱软件外包平台挑选指南与避坑清单!
java·后端·面试
皮皮林5512 天前
利用闲置 Mac 从零部署 OpenClaw 教程 !
java
华仔啊2 天前
挖到了 1 个 Java 小特性:var,用完就回不去了
java·后端
SimonKing2 天前
SpringBoot整合秘笈:让Mybatis用上Calcite,实现统一SQL查询
java·后端·程序员
日月云棠3 天前
各版本JDK对比:JDK 25 特性详解
java