ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

Leetcode 1232 缀点成线【简单】

2021-01-17 12:30:03  阅读:203  来源: 互联网

标签:return 1232 point int float coordinates point2 缀点 Leetcode


Leetcode 1232 缀点成线【简单】

题目描述

在一个 XY 坐标系中有一些点,我们用数组 coordinates 来分别记录它们的坐标,其中 coordinates[i] = [x, y] 表示横坐标为 x、纵坐标为 y 的点。

请你来判断,这些点是否在该坐标系中属于同一条直线上,是则返回 true,否则请返回 false。
在这里插入图片描述

示例 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 中不含重复的点

算法思想

分两种情况
①点在一条垂线上
②点不在一条垂线上
第一种情况,只需要检查各点的x坐标是否相同
第二种情况,选取两个点,计算f=kx+b
求出k和b,后续节点判断是否y == k
x + b

public class Solution {
    public boolean checkStraightLine(int[][] coordinates) {
        int []point1=coordinates[0];
        int []point2=coordinates[1];
        float k;
        float b;
        //先判断是否为垂线
        if(point2[0] - point1[0]==0){
            int x=point2[0];
            for(int i=2;i<coordinates.length;i++){
                int [] point=coordinates[i];
                if(point[0]==x){
                    continue;
                }else{
                    return false;
                }
            }
            return true;
        }else {
            k = (float) (point2[1] - point1[1]) / (float) (point2[0] - point1[0]);
            b = point2[1] - k * point2[0];
            for (int i = 2; i < coordinates.length; i++) {
                int[] point = coordinates[i];
                if (isLine(k, b, point)) {
                    continue;
                } else {
                    return false;
                }
            }
            return true;
        }
    }
    public boolean isLine(float k,float b,int [] point){
        if(point[1]!=(point[0]*k+b)){
            return false;
        }else{
            return true;
        }
    }
}

注意点:一开始我想try-catch到ArithmeticException来处理point2[0] - point1[0]=0的情况,后来发现并不能catch到,主要是因为float型的数值,如果做除法,即使除数为零也不会报错,此时返回的是null值

标签:return,1232,point,int,float,coordinates,point2,缀点,Leetcode
来源: https://blog.csdn.net/weixin_42080146/article/details/112736122

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有