447. Number of Boomerangs(easy)
Example:
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]]
----------------------------------------分割线-------------------------------------------
今天运气不错,pick one拿了一道水题。题目要求所有满足要求的有序三元组[i,j,k]的个数,其中i,j,k分别都是一个二维坐标。具体要求为:i和j的距离 与 i和k的笛卡尔距离相等。数据量为最多500个大小再[-1w,1w]的整数坐标。
之所以说是水题,主要是因为数据量只有500,直接一个暴力的O(n2)的枚举就可以了,目标也清晰明了。举个例子来描述我的想法。比如说给出有ABCDE五个点,首先计算任意两个点的距离,然后枚举圆心:以A为圆心,找到所有点里与A距离相等的点集(比如说BD两个点与A的距离相等),最后排列组合一下就能出结果了(ABD,ADB),接着再枚举下一个点…
具体做法,用外层循环来计算距离并且枚举圆心,内层循环计算得到距离以后,用一个map<distance,times>统计距离相同的点的个数。最后用组合数学来计算符合题目的三元组的个数即可(比如说统计得到距离为1的点个数为5,那符合题意得三元组即为A(5,2))。
细节方面:
1.记得每次枚举完一个点需要清空map;
2.由于数值计算得误差存在,存入map的distance的值我只保留了5位小数。
代码:
class Solution{
public:
int numberOfBoomerangs(vector<pair<int,int>>& points){
int len = points.size();
int ans = 0;
map<double,int> m;
for (int i = 0 ; i < len ;i++){
pair<int,int> a = points[i];
m.clear();
for (int j = 0; j < len ; j++){
if (j == i) continue;
pair<int,int> b = points[j];
double dis = sqrt((a.first-b.first)*(a.first-b.first)+(a.second-b.second)*(a.second-b.second));
dis = long(dis * 1e6)*1.0/1e6;
m[dis]++;
}
map<double,int>::iterator it;
for (it = m.begin() ; it != m.end() ; it ++)
if (it->second > 1){
ans += (it->second * (it->second -1));
}
}
return ans;
}
};
-------------------------------------分割线---------------------------------------------
题解:普遍都是使用hashMap, 时间复杂度O(n^2),和我的基本一样,就不细看了。