letecode [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]]
题目大意:
给定平面上 n 对不同的点,“回旋镖” 是由点表示的元组 (i, j, k) ,其中 i 和 j 之间的距离和 i 和 k 之间的距离相等(需要考虑元组的顺序)。找到所有回旋镖的数量。
理 解:
固定点 i ,计算它与其他节点的距离。用ordered_map保存。若有x个点与 i 的距离为dis,则排列方法有x * (x-1) 种。
ordered_map若某key存在则可访问,不存在则插入数据,value默认为0。ordered_map[key]。
代 码 C++:
class Solution { public: int numberOfBoomerangs(vector<vector<int>>& points) { int sum = 0,x,y; for(int i=0;i<points.size();++i){ unordered_map<int,int> couple; for(int j=0;j<points.size();++j){ x = (points[i][0]-points[j][0]); y = (points[i][1]-points[j][1]); ++couple[x*x+y*y]; } for(auto itr=couple.begin();itr!=couple.end();itr++){ sum += itr->second*(itr->second - 1); } } return sum; } };
运行结果:
执行用时 :644 ms, 在所有 C++ 提交中击败了83.13%的用户
内存消耗 :134 MB, 在所有 C++ 提交中击败了29.54%的用户