【LeetCode】149. 直线上最多的点数

简介: 【LeetCode】149. 直线上最多的点数

题目链接

149. 直线上最多的点数

题目简介

给你一个数组points ,其中 points[i] = [xi, yi] 表示 X-Y 平面上的一个点。求最多有多少个点在同一条直线上。

示例 1:

输入:points = [[1,1],[2,2],[3,3]]
输出:3

题目解析

  1. 1.给定一些点,求哪些点在一条直线上
  2. 2.常见的做法有两种:
  • 第一种:计算每个点和其他点的斜率比(y2 - y1)/ (x2 - x1),将斜率比按 数值 存进 map
  • 第二种:计算每个点和其他点的斜率比(y2 - y1)/ (x2 - x1),将斜率比按 字符串 存进 map

3.这里需要注意一下,我们在计算斜率的时候,会出现分母为0的情况,在C++中不影响程序的运行,但是在Java中是影响程序运行的。我们去看下Java官方关于这一块的定义:

Thrown when an exceptional arithmetic condition has occurred. 
For example, an integer "divide by zero" throws an instance of this class.
当出现异常的运算条件时,抛出此异常。
例如,一个整数“除以零”时,抛出此类的一个实例。
  1. 所以,我们需要在我们整除的时候,将分子置为 小数 类型

题目代码

class Solution {
    public int maxPoints(int[][] points) {
        if(points.length == 1){
            return 1;
        }
        int max = 0;
        for (int i = 0; i < points.length; i++) {
            int x = points[i][0];
            int y = points[i][1];
            HashMap<Double, Integer> map = new HashMap<>();
            for (int j = 0; j < points.length; j++) {
                if (j != i) {
                    double target = ((points[j][1] - y) * 1.0)  / (points[j][0] - x);
                    if (map.containsKey(target)) {
                        int value = map.get(target);
                        map.put(target, ++value);
                    } else {
                        map.put(target, 2);
                    }
                }
            }
            for (Map.Entry<Double, Integer> entry : map.entrySet()) {
                max = Math.max(max, entry.getValue());
            }
        }
        return max;
    }
}












相关文章
【LeetCode】1423. 可获得的最大点数
【LeetCode】1423. 可获得的最大点数
|
5月前
|
算法 vr&ar 图形学
☆打卡算法☆LeetCode 149. 直线上最多的点数 算法解析
☆打卡算法☆LeetCode 149. 直线上最多的点数 算法解析
|
Java C++
LeetCode(剑指 Offer)- 60. n个骰子的点数
LeetCode(剑指 Offer)- 60. n个骰子的点数
78 0
LeetCode(剑指 Offer)- 60. n个骰子的点数
|
数据库
LeetCode(数据库)- 直线上的最近距离
LeetCode(数据库)- 直线上的最近距离
68 0
|
2月前
|
机器学习/深度学习 算法
力扣刷题日常(一)
力扣刷题日常(一)
20 2
|
2月前
|
存储 索引
《LeetCode》—— LeetCode刷题日记
《LeetCode》—— LeetCode刷题日记
|
2月前
|
搜索推荐
《LeetCode》——LeetCode刷题日记3
《LeetCode》——LeetCode刷题日记3
|
2月前
|
容器
《LeetCode》——LeetCode刷题日记1
《LeetCode》——LeetCode刷题日记1

热门文章

最新文章