149. 直線上最多的點數 沒有通過---

149. 直線上最多的點數

難度困難132收藏分享切換爲英文關注反饋

給定一個二維平面,平面上有 個點,求最多有多少個點在同一條直線上。

示例 1:

輸入: [[1,1],[2,2],[3,3]]
輸出: 3
解釋:
^
|
|        o
|     o
|  o  
+------------->
0  1  2  3  4

示例 2:

輸入: [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]]
輸出: 4
解釋:
^
|
|  o
|     o        o
|        o
|  o        o
+------------------->
0  1  2  3  4  5  6

 

 

class Solution {
public:
    int maxPoints(vector<vector<int>>& points) {
       if(points.empty()){
           return 0;
       }    
       unordered_map<long double, int> hash;

       int result = 1;
       for(int i =0; i< points.size() ; i++){
              int vertical = 1;
              int duplicate =0;

              for (int j =i+1 ; j<points.size();j++ ){
                  if (points[i][0] == points[j][0]) {
                       vertical ++;
                       if (points[i][1] == points[j][1]) {
                           duplicate++;   
                        } 
                   } 
                }

                for (int j =i + 1; j<points.size(); j++){

                   if(points[i][0] != points[j][0] ) {
                        long double slope = (long double)  (points[i][1] - points[j][1]) / (points[i][0] - points[j][0]);
                            if(!hash.count(slope)) hash[slope] =2;
                            else {
                                    hash[slope] ++;
                            }
                            result = max(result ,hash[slope] + duplicate);
                    }
                }
        result = max(result,vertical);    
       }    
       return result;
    }
};

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章