leetcode 447. Number of Boomerangs

Given n points in the plane that are all pairwise distinct, a "boomerang" is a tuple of points (i, j, k) such that the distance between i and j equals the distance between i and k (the order of the tuple matters).

Find the number of boomerangs. You may assume that n will be at most 500 and coordinates of points are all in the range [-10000, 10000] (inclusive).

Example:

Input:
[[0,0],[1,0],[2,0]]

Output:
2

Explanation:
The two boomerangs are [[1,0],[0,0],[2,0]] and [[1,0],[2,0],[0,0]]

思路,枚举。

观察元组我们发现满足条件的元组(i,j,k)(i,j)的距离等于 (i,k)的距离,那么我们可以枚举i然后找到符合条件的j,k统计个数就行了,但是这样枚举暴力的方法是O(n^3)的复杂度,由于n=500代码接近1e9的计算量,所以我们得换个姿势。

同样是枚举i,再枚举j,然后我们用map记录i到j的长度出现过几次,在枚举k的时候,计算i,k的距离,看map中dis(i,k)出现过几次,如果出现m次,那么就加上m-1。(想一想为什么加上m-1)。

代码如下:

class Solution {
public:
    int dis(pair<int, int> a, pair<int, int> b) {
        return (a.first - b.first) * (a.first - b.first) + (a.second - b.second) * (a.second - b.second);
    }
    int numberOfBoomerangs(vector<pair<int, int>>& points) {
        map<int, int> mp;
        int ans = 0, x;
        for (int i = 0; i < points.size(); ++i) {
            for (int j = 0; j < points.size(); ++j) {
                x = dis(points[i], points[j]);
                if (x == 0) continue;
                mp[x]++;
            }
            for (int k = 0; k < points.size(); ++k) {
                int x = dis(points[i], points[k]);
                if (mp[x]) {
                    ans += (mp[x] - 1);
                }
            }
            mp.clear();
        }
        return ans;
    }
};
原文地址:https://www.cnblogs.com/pk28/p/7456523.html