LeetCode-多点共线

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

/**
 * 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 maxPoints(vector<Point> &points) {
        
        if (points.size() == 0)
            return 0;
        
        if (points.size() == 1)
            return 1;
        
        int result = 0;
        double k;
        for (int i = 0;i < points.size();i++){
            map<double,int> kMap;
            int reCount = 0;//重复的点
            int vCount = 1;//竖直的计数
            int currentMax = 1;//当前最大值存储
            
            for (int j = i+1;j < points.size();j++){
                
                if (points[i].x == points[j].x && points[i].y == points[j].y){
                    reCount++;
                }else{
                    
                    if (points[i].x == points[j].x){
                        vCount++;
                        currentMax = max(currentMax,vCount);
                    }else{
                        
                        k = 1.0 * (points[j].y-points[i].y) / (points[j].x-points[i].x);
                        
                        if (kMap[k] == 0)
                            kMap[k] = 2;
                        else
                            kMap[k]++;
                    }
                }
                currentMax = max(kMap[k],currentMax);
            }
            result = max(result,currentMax+reCount);
        }
        return result;
    }
};

按照给出的提示,本题采用的是穷举的思路。
将所有的情况列举出来,这条占点最多的线自然就求出来了。

1、首先,我们将0个点和1个点的情况筛选出来
2、考虑共线的条件:{
斜率相等
竖直
两点相同
}
3、循环走起😄
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,916评论 0 23
  • 1排石小贴士 有朋友说,排石我嫌麻烦,我身体挺好的,光喝苹果汁行不行? 我来告诉你:喝苹果汁最多能...
    邱小兰悦阅读 10,911评论 1 9
  • 我是一期一班的学生,从2017年元月九号开始到现在,混搭在悦读写作圈足有半年多时间了,期间聆听着各位老师的教导,见...
    非常道_faae阅读 562评论 16 18
  • 一本书的美好,最好能让人想到童年。 在我们都是孩子的时侯,在大家以一种无知而期盼的眼神迎接未来的时侯,在我们一天天...
    simbfry阅读 472评论 0 0