LeetCode 447 Number of Boomerangs

Posted SillyVicky

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 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 iand 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]]

Summary:

定义一种类似“回形标”的三元组结构,即在三元组(i, j, k)中i和j之间的距离与i和k之间的距离相等。找到一组坐标数据中,可构成几组这样的“回形标”结构。

Analysis:

若在一组点集{a, b, c, d, ...}中,以点a为一个端点,与dis(a, b)相等的点存在n个(包含点b),那么在这n个点中任意选出两个点与点a构成三元组,则有n(n - 1) / 2种情况。但因为三元组[a, b, c]与三元组[a, c, b]并不相同,所以实际为排列问题,答案为n(n - 1)。

代码中正是以此为基本思想,找到以每一个点为端点时,与其余点共组成多少种不同的距离,此处用map记录,key为距离长度,value为距离出现次数。再根据前面的公式计算即可。

 1 class Solution {
 2 public:
 3     int numberOfBoomerangs(vector<pair<int, int>>& points) {
 4         int len = points.size(), res = 0;
 5         unordered_map<int, int> m;
 6         
 7         for (int i = 0; i < len; i++) {
 8             for (int j = 0; j < len; j++) {
 9                 int x = points[i].first - points[j].first;
10                 int y = points[i].second - points[j].second;
11                 m[x * x + y * y]++;
12             }
13             
14             unordered_map<int, int> :: iterator it;
15             for (it = m.begin(); it != m.end(); it++) {
16                 int tmp = it->second;
17                 res += tmp * (tmp - 1);
18             }
19             m.clear();
20         }
21         
22         return res;
23     }
24 };

以上是关于LeetCode 447 Number of Boomerangs的主要内容,如果未能解决你的问题,请参考以下文章

leetcode447-Number of Boomerangs

[LeetCode]447 Number of Boomerangs

leetcode 447 Number of Boomerangs

Leetcode 447. Number of Boomerangs JAVA语言

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

[LeetCode 1274] Number of Ships in a Rectangle