每日一题 21.01.17 LeetCode 1232. 缀点成线 Java题解

题目

https://leetcode-cn.com/problems/check-if-it-is-a-straight-line/
在这里插入图片描述

思路

我的代码思路,设y=ax+b,不咋好。

官方题解:为方便后续计算,将所有点向 (-P0x, -P0y)方向平移。平移后的p0’在坐标原点O上。
直线过原点,故设其方程为 Ax+By=0。

代码

class Solution {
    public boolean checkStraightLine(int[][] coordinates) {
        int len=coordinates.length;
        if(len==0||len==1||len==2)
            return true;

        int x0=coordinates[0][0];
        int y0=coordinates[0][1];
        int x1=coordinates[1][0];
        int y1=coordinates[1][1];
        int flag=0;
        if(x1-x0==0){
            flag=1;
        }
        double a=(y1-y0)*1.0/(x1-x0);
        double b=y1-a*x1;
        for(int i=1;i<len;i++){
            int[] cp=coordinates[i];
            int x=cp[0];
            int y=cp[1];
            if(flag==1){
                if(x!=x1)
                    return false;
            }
            else{
                if((a*x+b)!=y)
                    return false;
            }
        }
        return true;
    }
}
class Solution {
    public boolean checkStraightLine(int[][] coordinates) {
        int deltaX = coordinates[0][0], deltaY = coordinates[0][1];
        int n = coordinates.length;
        for (int i = 0; i < n; i++) {
            coordinates[i][0] -= deltaX;
            coordinates[i][1] -= deltaY;
        }
        int A = coordinates[1][1], B = -coordinates[1][0];
        for (int i = 2; i < n; i++) {
            int x = coordinates[i][0], y = coordinates[i][1];
            if (A * x + B * y != 0) {
                return false;
            }
        }
        return true;
    }
}

结果

在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值