LeetCode 149. Max Points on a Line

#include <unordered_map>
#include <vector>
#include <iostream>
#include <climits>
using namespace std;

struct Point {
  int x;
  int y;
  Point() : x(0), y(0) {}
  Point(int a, int b) : x(a), y(b) {}
};

/*
  Two caculate two points are on the same line:
  (x1, y1), (x2, y2)
  We need to cacualte that res = (x1 - x2) / (y1 - y2), push the HashMap[res]++;
  However, there are several cases to cacualte res.
  1: y1 == y2  --> divisor equals to 0, in this case, we can store INT_MAX as key.
  2: x1 == x2 && y1 == y2, duplicate points, we can stop storing it, use a duplicate counter instead.
*/
int maxPoints(vector<Point>& points) {
  unordered_map<float, int> hashMap;
  int maxCount = 0;
  for(int i = 0; i < points.size(); ++i) {
    hashMap.clear();
    hashMap[INT_MIN] = 0;
    int duplicate = 1;
    for(int j = 0; j < points.size(); ++j) {
      if(j == i) continue; // skip the same point.
      if((points[i].x == points[j].x) && (points[i].y == points[j].y)) {duplicate++; continue;}
      else if(points[i].x == points[j].x) {hashMap[INT_MIN]++;}
      else {
        float k = (float)(points[j].y - points[i].y) / (points[j].x - points[i].x);
        hashMap[k]++;
      }
    }
    auto iter = hashMap.begin();
    while(iter != hashMap.end()) {
      maxCount = max(maxCount, iter->second + duplicate);
      iter++;
    }
  }
  return maxCount;
}

int main(void) {
  // contains duplicates.
  vector<Point> test_1{Point(1,1), Point(1, 2), Point(1, 1), Point(1, 1)};
  cout << maxPoints(test_1) << endl;
   // on the same x line.
  vector<Point> test_2{Point(1,1), Point(1, 3), Point(1, 4), Point(1, 5)};
  cout << maxPoints(test_2) << endl;

  // on the same line.
  vector<Point> test_3{Point(1,1), Point(2, 2), Point(3, 3), Point(4, 4)};
  cout << maxPoints(test_3) << endl;

  // on same y line.
  vector<Point> test_4{Point(2,1), Point(3, 1), Point(4, 1), Point(5, 1)};
  cout << maxPoints(test_4) << endl;

  // make a mix.
  vector<Point> test_5{Point(2, 2), Point(3, 3), Point(4, 4), Point(3, 1), Point(4, 1), Point(5, 1), Point(1, 3), Point(1, 4), Point(1, 5)};
  cout << maxPoints(test_5) << endl;
}


你可能感兴趣的:(LeetCode 149. Max Points on a Line)