zoukankan      html  css  js  c++  java
  • 1232. Check If It Is a Straight Line

    You are given an array coordinatescoordinates[i] = [x, y], where [x, y] represents the coordinate of a point. Check if these points make a straight line in the XY plane.

    Example 1:

    Input: coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]]
    Output: true
    

    Example 2:

    Input: coordinates = [[1,1],[2,2],[3,4],[4,5],[5,6],[7,7]]
    Output: false
    

    Constraints:

    • 2 <= coordinates.length <= 1000
    • coordinates[i].length == 2
    • -10^4 <= coordinates[i][0], coordinates[i][1] <= 10^4
    • coordinates contains no duplicate point.
    class Solution {
        public boolean checkStraightLine(int[][] coordinates) {
            double k = (double)(coordinates[1][1] - coordinates[0][1]) / (coordinates[1][0] - coordinates[0][0]);
            for(int i = 2; i < coordinates.length; i++){
                double kt = (double)(coordinates[i][1] - coordinates[i-1][1]) / (coordinates[i][0] - coordinates[i-1][0]);
                if(k != kt) return false;
            }
            return true;
        }
    }

    先想到bruteforce,比较每两个点的斜率,注意4/5在int的时候是0,要先(double) 4/5这样。然后比较就可.

    class Solution {
        public boolean checkStraightLine(int[][] coordinates) {
            int t1 = coordinates[1][1] - coordinates[0][1];        
            int t2 = coordinates[1][0] - coordinates[0][0];
            
            for(int i = 2; i < coordinates.length; i++){
                if((coordinates[i][1] - coordinates[i-1][1]) * t2 != t1 * (coordinates[i][0] - coordinates[i-1][0])) return false;
            }
            return true;
        }
    }

     然后这个方法用上面的公式,不求斜率直接比交叉的积,不相同就return false

  • 相关阅读:
    爬虫
    modelform
    验证码
    ajax
    ngnix和负载均衡
    django 补充和中间件
    django补充和form组件
    C常量与控制语句
    Web应用开发技术(3)-html
    Web应用开发技术(2)-html
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/12854692.html
Copyright © 2011-2022 走看看