Leetcode 149. Max Points on a Line同一条直线上的最多点数

Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.

Example 1:

Input: [[1,1],[2,2],[3,3]]
Output: 3
Explanation:
^
|
|        o
|     o
|  o  
+------------->
0  1  2  3  4

Example 2:

Input: [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]]
Output: 4
Explanation:
^
|
|  o
|     o        o
|        o
|  o        o
+------------------->
0  1  2  3  4  5  6

题目链接:https://leetcode.com/problems/max-points-on-a-line/

思路:首先是一种暴力的解法,三重循环,任意2个点组成一条直线,再重n个点中,依次判断在不在这条直线上

/**
 * Definition for a point.
 * struct Point {
 *      int x;
 *      int y;
 *     Point() : x(0), y(0) {}
 *     Point(int a, int b) : x(a), y(b) {}
 * };
 */
class Solution {
    long long coline(Point a,Point b,Point c){ /*check whether the three points are on the same line*/
        return (long long)(a.x-c.x)*(b.y-c.y)==(long long)(a.y-c.y)*(b.x-c.x);
    }
public:
    int maxPoints(vector& points) {
        int n = points.size();
        int max_pts = 0;
        for(int i=0;i

Leetcode 149. Max Points on a Line同一条直线上的最多点数_第1张图片

更快的方法,用map保存<斜率(kx,ky),个数>

关于duplicate,用于保存相同的点的个数

顺便也复习了最大公约数(辗转相除法)hhh

Leetcode 149. Max Points on a Line同一条直线上的最多点数_第2张图片

/**
 * Definition for a point.
 * struct Point {
 *      int x;
 *      int y;
 *     Point() : x(0), y(0) {}
 *     Point(int a, int b) : x(a), y(b) {}
 * };
 */
class Solution {
    public:
    
    int gcd(int x,int y)
    {
        while(y!=0)
        {
            int t=x%y;
            x=y;
            y=t;
        }
        return x;
    }
    int maxPoints(vector& points) {
         int res=0;
        int n=points.size();
        int duplicate=0;
        map,int> m;
        for(int i=0;ires;i++)
        {
            duplicate=1;
            for(int j=i+1;j

 

Leetcode 149. Max Points on a Line同一条直线上的最多点数_第3张图片

你可能感兴趣的:(Leetcode)