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

    Runtime: 40ms

     1 /**
     2  * Definition for a point.
     3  * struct Point {
     4  *     int x;
     5  *     int y;
     6  *     Point() : x(0), y(0) {}
     7  *     Point(int a, int b) : x(a), y(b) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     int maxPoints(vector<Point>& points) {
    13         int n = points.size();
    14         if(n <= 2) return n;
    15         
    16         int result = 0;
    17         for(int i = 0; i < points.size(); i++){
    18             unordered_map<double, int> m;
    19             m[INT_MIN] = 0;
    20             m.clear();
    21             int duplicate = 1;
    22             for(int j = 0; j < points.size(); j++){
    23                 if(i != j){
    24                     if(points[i].x == points[j].x && points[i].y == points[j].y)
    25                         duplicate++;
    26                     else{
    27                         double key = (points[i].x == points[j].x ? INT_MAX : (1.0 * (points[i].y - points[j]. y) / (points[i].x - points[j].x)));
    28                         //m[key] = (m.find(key) == m.end() ? 2 : ++m[key]);
    29                         m[key]++;
    30                     }
    31                 }
    32             }
    33             if(m.empty()) result = max(result, duplicate);
    34             else{
    35                 for(unordered_map<double, int>::iterator ite = m.begin(); ite != m.end(); ite++)
    36                     result = max(result, duplicate + ite->second);
    37             }
    38         }
    39         return result;
    40     }
    41 };
  • 相关阅读:
    c# 面相对象4-多态性
    c# 面相对象3-之继承性
    c# 面相对象2-之封装性
    面向对象和面向过程的区别
    <title>下拉菜单</title>
    15-07-31 javascript--事件
    DOM操作
    格式与布局
    c# 函数相关练习
    c# 哈希表集合;函数
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4870602.html
Copyright © 2011-2022 走看看