(轉)Max Points on a Line

來源:互聯網
上載者:User

標籤:

轉:http://blog.csdn.net/doc_sgl/article/details/17103427

這道題思想很簡單··············

分析:

任意一條直線都可以表述為

y = ax + b

假設,有兩個點(x1,y1), (x2,y2),如果他們都在這條直線上則有

y1 = kx1 +b

y2 = kx2 +b

由此可以得到關係,k = (y2-y1)/(x2-x1)。即如果點c和點a的斜率為k, 而點b和點a的斜率也為k,可以知道點c和點b也在一條線上。

取定一個點points[i], 遍曆其他所有節點, 然後統計斜率相同的點數,並求取最大值即可。

/** * 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) {         unordered_map<float,int> mp;          int maxNum = 0;          for(int i = 0; i < points.size(); i++)          {              mp.clear();              mp[INT_MIN] = 0;              int duplicate = 1;              for(int j = 0; j < points.size(); j++)              {                  if(j == i) continue;                  if(points[i].x == points[j].x && points[i].y == points[j].y)                  {                      duplicate++;                      continue;                  }                  float k = points[i].x == points[j].x ? INT_MAX : (float)(points[j].y - points[i].y)/(points[j].x - points[i].x);                  mp[k]++;              }              unordered_map<float, int>::iterator it = mp.begin();              for(; it != mp.end(); it++)                  if(it->second + duplicate > maxNum)                      maxNum = it->second + duplicate;          }          return maxNum;              }};

注意:

 

0、points中重複出現的點。

1、int maxNum = 0;

初始化,以防points.size() ==0的情況。

2、mp[INT_MIN] = 0;

保證poins中只有一個結點,還有points中只有重複元素時,mp中沒有元素。這兩種極端情況。

3、int duplicate = 1;

duplicate記錄重複點的數量,初始化為1,是因為要把當前的點points[i]加進去。

4、float k = points[i].x == points[j].x ? INT_MAX : (float)(points[j].y - points[i].y)/(points[j].x - points[i].x);

計算斜率,如果直線和y軸平行,就取INT_MAX,否則就取(float)(points[j].y - points[i].y)/(points[j].x - points[i].x)

一開始把(float)(points[j].y - points[i].y)/(points[j].x - points[i].x)寫做(float)((points[j].y - points[i].y)/(points[j].x - points[i].x))一直就不對,後來才想明白,注意注意!

(轉)Max Points on a Line

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.