C++ code without using pair or nested hashmap


  • 0
    J
    class Solution {
    public:
        int maxPoints(vector<Point>& points) {
            if (points.size() <= 2) return points.size();
            int result = 0;
            for (int i = 0; i < points.size(); i++) {
                int over_lap = 0;
                int slope_inf = 0;
                int slope_max = 0;
                unordered_map<string, int> slope;
                for (int j = i + 1; j < points.size(); j++) {
    
                    //double k = 0.0;
                    if (points[i].x == points[j].x && points[i].y == points[j].y) 
                        over_lap++;
                    else if (points[i].x == points[j].x && points[i].y != points[j].y)
                        slope_inf++;
                    else {
                        //k = (double)(points[i].y - points[j].y) / ((double)(points[i].x - points[j].x));
                        int gcd = find_gcd(points[i].y - points[j].y, points[i].x - points[j].x);
                        string k = to_string((points[i].y - points[j].y) / gcd) + "," 
                            + to_string((points[i].x - points[j].x) / gcd);
                        if (slope.count(k)) slope[k]++;
                        else slope.insert({k, 1});
                        slope_max = max(slope_max, slope[k]);   
                    }
                    
                }
                result = max(result, max(slope_inf, slope_max) + over_lap);  
            }
            return result + 1;
        }
    private:
        int find_gcd(int i, int j) {
            if (j == 0) return i;
            return find_gcd(j, i % j);
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.