• 缀点成线


    此博客链接:https://www.cnblogs.com/ping2yingshi/p/14290850.html

    缀点成线

    题目链接:https://leetcode-cn.com/problems/check-if-it-is-a-straight-line/submissions/

    题目

    在一个 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

    题解

    此题利用斜率比较是否相等,如果邪路全部相等则在一条直线上,这里需要注意两点:

    1.整数相除时要转换为浮点数。

    2.需要考虑斜率为90度情况。

    代码

    class Solution {
        public boolean checkStraightLine(int[][] coordinates) {
              int len=coordinates.length;
              int count=0;
            if(coordinates[0][0]==0&&coordinates[1][0]==0)
            {
                for(int i=2;i<len;i++)
                {
                    if(coordinates[i][0]!=0)
                    {
                        return false;
                    }
                    else{
                        count++;
                    }
                }
                if(count==len-2)
                return true;
            }
          
            int [][]start=new int[1][2];
            start[0][0]=coordinates[0][0];
            start[0][1]=coordinates[0][1];
            double xielv=0.0;
            xielv=(coordinates[1][1]-start[0][1]+0.0d)/(coordinates[1][0]-start[0][0]+0.0d);
            double temp=0.0;
            for(int i=2;i<len;i++)
            {
                
                    temp=(coordinates[i][1]-start[0][1]+0.0d)/(coordinates[i][0]-start[0][0]+0.0d);
                    if(temp!=xielv)
                    {
                        return false;
                    }
                
            }
            return true;
        }
    }

    结果

    出来混总是要还的
  • 相关阅读:
    类加载器
    hibernate笔记
    windows笔记
    maven笔记
    mysql笔记
    jsonp使用
    [ZJU 1010] Area
    [ZJU 1004] Anagrams by Stack
    [ZJU 1003] Crashing Balloon
    [ZJU 1002] Fire Net
  • 原文地址:https://www.cnblogs.com/ping2yingshi/p/14290850.html
Copyright © 2020-2023  润新知