LeetCode 447. Number of Boomerangs; 149. Max Points on a Line

Boomerang 回旋镖的意思,本题意思是寻找 abc的点对,使得ab,ac距离相等。

一个循环固定a,计算其余的点到a的距离,简历一个hashtable,保存对应距离的点的个数。

如果有n个点到a距离相等,那么一共有 P_n^2 种可能 (题目中提到不同顺序算多种)

class Solution {
public:
    int numberOfBoomerangs(vector<pair<int, int>>& points) {
        int res=0;
        for (int i=0;i<points.size();++i){
            unordered_map<int,int> count; // <dis^2, numbers>
            for (int j=0;j<points.size();++j){
                if (i==j) continue;
                int dx=points[i].first-points[j].first;
                int dy=points[i].second-points[j].second;
                ++count[dx*dx+dy*dy];
            }
            for (auto i:count){ // P_n^2 since order matters
                int n=i.second;
                res += n*(n-1);
            }
        }
        return res;
    }
};

149. Max Points on a Line

思路和上一题一样,固定一个点,计算其余的点与当前的斜率,建立hashtable保存相同的斜率数目。

本题j循环从i+1开始就行了,不用重复计算。注意,与x轴垂直的两点是没法计算斜率的,需要单独计算;此外,还要考虑重复的点的问题。

这道题还有一个坑,由于double的精度问题,用 <double,int> 来开hashtable 不能ac,因此可以用 <dy/gcd, dx/gcd> 来保存斜率,用这种方法的话 与x轴垂直的点也可以包括在内。

顺便复习一下辗转相除法的写法。

/**
 * 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) {
        int res=0;
        for (int i=0;i<points.size();++i){
            map<pair<int,int>,int> count; // <slope, num>
            int vertical=0;
            int depulicate=1; // one is for itself
            for (int j=i+1;j<points.size();++j){
                if (points[i].x==points[j].x && points[i].y==points[j].y) {++depulicate; continue;}
                //if (points[i].x==points[j].x) {++vertical; continue;} //can be omitted now
                int dy=points[i].y-points[j].y;
                int dx=points[i].x-points[j].x;
                int gcd=GCD(dx,dy);
                ++count[{dy/gcd, dx/gcd}];
            }
            for (auto x:count){
                res = max(res, x.second+depulicate);
            }
            //res = max(res,vertical+depulicate);
            res = max(res, depulicate);
        }
        return res;
    }
    
    int GCD(int a, int b){
        return b==0? a : GCD(b,a%b);
    }
};

猜你喜欢

转载自www.cnblogs.com/hankunyan/p/9557875.html