leetCode-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 个点,一个boomerang是一个元组点,其中 i  j 的距离等于 i  k 的距离(元组内部有序)。

找到boomerangs的个数。你可以假设 n 最多为500并且点的坐标在范围[-10000,10000](包括)内。

例子:

输入:
[[0,0],[1,0],[2,0]]

输出:
2

解释:
两个boomerangs是 [[1,0],[0,0],[2,0]][[1,0],[2,0],[0,0]]


思路:

题意不好理解,实际是想遍历计算每一点到其余各点距离相同的有多少,然后将这些距离相同的点排列成三元组的形式有多少种排列方法。先用map计算各点距离相等的个数,至于排列的方法数,是一个组合问题 C=(5,3)*2,即 n*(n-1) 。


C++(Visual Studio 2017):

#include "stdafx.h"
#include <iostream>
#include <vector>
#include <map>
using namespace std;

class Solution {
public:
	int numberOfBoomerangs(vector<pair<int, int>>& points) {
		int result=0;
		for (int i = 0; i < points.size(); i++) {
			map<int, int> m;
			for (int j = 0; j < points.size(); j++) {
				int a = points[i].first - points[j].first;
				int b = points[i].second - points[j].second;
				m[a*a + b*b]++;
			}
			for (auto it = m.begin(); it != m.end(); it++) {
				result += it->second * (it->second - 1);
			}
		}
		return result;
	}
};

int main()
{
	Solution s;
	vector<pair<int, int>> points = { {0,0},{1,0},{2,0} };
	int result;
	result = s.numberOfBoomerangs(points);
	cout << result;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/tel_annie/article/details/80392015