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

  • 相关阅读:
    分布式git
    服务器上的git
    git分支
    剑指offer(38)二叉树的深度
    剑指offer(37)数字在排序数组中出现的次数。
    JS刷题总结
    剑指offer(36)两个链表中的第一个公共节点
    剑指offer(35)数组中的逆序对
    剑指offer(34)第一个只出现一次的字符
    剑指offer(33)丑数
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/12854692.html
Copyright © 2011-2022 走看看