447. Number of Boomerangs

Problem:

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]]

思路

Solution (C++):

int numberOfBoomerangs(vector<vector<int>>& points) {
    if (points.empty() || points[0].empty()) return 0;
    int m = points.size(), count = 0, res = 0;
    vector<int> dis(m, 0);
    for (int i = 0; i < m; ++i) {
        for (int j = 0; j < m; ++j) {
            if (i == j) dis[j] = 0;
            dis[j] = distance(points[i], points[j]);                
        }
        sort(dis.begin(), dis.end());
        for (int k = 0; k < m-1; ++k) {
            while (k < m-1 && dis[k] == dis[k+1]) { count++; k++; }
            if (count >= 2)  res += An2(count);
            count = 1;
        }
    }
    return res;
}
int distance(vector<int> v1, vector<int> v2) {
    return pow(v2[0]-v1[0], 2) + pow(v2[1]-v1[1], 2);
}
int An2(int n) {
    return n * (n-1);
}

性能

Runtime: 1416 ms  Memory Usage: 161.7 MB

思路

Solution (C++):


性能

Runtime: ms  Memory Usage: MB

posted @ 2020-04-01 17:08  littledy  阅读(108)  评论(0编辑  收藏  举报