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;
    }
}
相关推荐
zhangfeng113317 小时前
台大李宏毅老师讲解memba和类似linear atttenion 模型,笔记
开发语言·人工智能·笔记
Chris _data18 小时前
并发单词频率统计器 - 从零到完整实现(C# 实战)
开发语言·c#
idolao18 小时前
Oligo 7.60 安装教程:引物设计+Java 环境配置
java·开发语言
不知名的老吴18 小时前
Lambda表达式与新的Streams API相结合
开发语言·python
做个文艺程序员21 小时前
第04篇:K8s 弹性伸缩实战:HPA、VPA、KEDA——Java SaaS 应对流量洪峰的秘密武器
java·容器·kubernetes·弹性伸缩·自动扩容·ai 推理伸缩
石山代码1 天前
ArrayList / HashMap / ConcurrentHashMap
java·开发语言
程序大视界1 天前
【Python系列课程】Python正则表达式(下):环视、命名分组与日志实战
开发语言·python·正则表达式
枫叶v.1 天前
Agent 分层存储架构设计:从记忆方法到中间件选型
开发语言·python
AskHarries1 天前
系统提示词、开发者指令和用户输入的优先级
java·前端·数据库
daidaidaiyu1 天前
ThingsBoard 规则链系统源码分析和自定义定时器
java