1237. 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).

您在真實的面試中是否遇到過這個題?  

樣例

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

沒有什麼特別討巧的辦法,只能是使用關聯容器儲存每對點之間的距離,然後再算出一共有多少組。

class Solution {
public:
    /**
     * @param points: a 2D array
     * @return: the number of boomerangs
     */
    int numberOfBoomerangs(vector<vector<int>> &points) {
        // Write your code here
        int result=0;
        for(int i=0;i<points.size();i++){
            unordered_map<int,int> m_map;
            for(int j=0;j<points.size();j++){
                int a=points[i][0]-points[j][0];
                int b=points[i][1]-points[j][1];
                ++m_map[a*a+b*b];
            }
            for(auto it=m_map.begin();it!=m_map.end();++it){
                result+=it->second*(it->second-1);
            }
        }
        return result;
    }
};


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