[LeetCode OJ] Max Points on a 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) {}
 * };
 */
#include <iostream>
#include <stack>
#include <string>
#include <vector>
#include <cstdlib>
#include <tr1/unordered_map>
#define INF 0x7fffffff
class Solution {
public:
    int maxPoints(vector<Point> &points) {
        unordered_map<double,int> umap;
    unordered_map<double,int>::iterator it;
    int ans = 1;
    int size =points.size();
    if(size == 0)
        ans=0;
    for(int i=0; i<size; ++i){
        int sameCnt = 1;
        umap.clear();
        for(int j=i+1; j<size; ++j){
            double key;
            if(points[i].x == points[j].x && points[i].y == points[j].y){
                ++sameCnt;
                continue;
            }
            else if(points[i].x == points[j].x){
                key = INF;
            }
            else{
                key = (double)(points[j].y-points[i].y)/(double)(points[j].x-points[i].x);
            }
            it = umap.find(key);
            if(it == umap.end()){
                umap[key] = 1;
            }
            else{
                umap[key]++;
            }
        }
        ans = max(ans,sameCnt);//多点重合的情况,umap为空
        for(it = umap.begin(); it != umap.end(); ++it){
            ans = max(ans,it->second+sameCnt);
        }
    }
        return ans;
    }
};
点赞