zoukankan      html  css  js  c++  java
  • [LeetCode]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.

    思考:考虑以下几种情况:

    1.points中0、1、2个点;

    2.points含相同点如{[0,0],[0,0]},{[1,1],[1,1],[2,2],[2,2]}};

    3.斜率为无穷。

    /**
     * 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) {
            int n=points.size(); //point个数
            if(n<=2) return n;
            int i,j;
            int max=0;
            map<double,int> m; //每个point斜率集合
            for(i=0;i<n;i++)
            {
                m.clear();
    			m[INT_MAX]=0; //斜率为无穷
    			int samepoint=1; //相同点个数
                for(j=0;j<n;j++)
                {
    				if(i==j) continue;
    				if((points[j].x==points[i].x)&&(points[j].y==points[i].y)) samepoint++;
                    else if(points[j].x==points[i].x) m[INT_MAX]++;
                    else
                    {
                        double k=(double)(points[j].y-points[i].y)/(points[j].x-points[i].x); //斜率不为无穷	
                        if(m.find(k)==m.end()) m[k]=1;
    					else m[k]++;
                    }
                }
    			map<double,int>::iterator iter;
    			for(iter=m.begin();iter!=m.end();iter++)
    			{
    			//	cout<<iter->first<<" "<<iter->second+samepoint<<endl;
    				if(iter->second+samepoint>max) max=iter->second+samepoint;
    			}
            }
            return max;
        }
    };
    

      

  • 相关阅读:
    ZooKeeper详解
    数据结构与算法2——数组
    jquery复习笔记
    关于水平居中
    回顾这些日子
    阻止事件冒泡
    css导航栏
    js正则
    js事件绑定
    操作iframe
  • 原文地址:https://www.cnblogs.com/Rosanna/p/3496692.html
Copyright © 2011-2022 走看看