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

題意:要求計算所有滿足到點i的距離相等的有序元組[i, j, k],其中i、j、k代表座標點。

解決方案:對每個點i,計算其他所有點到點i的距離,並用一個map容器m存儲每個距離所對應的點的個數,對於每個距離d,每新增一個點j使得i與j之間的距離等於d,只需將ans加上2*m[d](由於j、k有序),並將m[d]++即可。

代碼實現如下:

class Solution {
public:
    int numberOfBoomerangs(vector<pair<int, int> >& points) {
    	int n = points.size(), ans = 0;
    	for(int i=0; i<n; i++)
    	{
    		map<int, int> m;
    		for(int j=0; j<n; j++)
			{
			    int dx = points[i].first-points[j].first, dy = points[i].second-points[j].second;
                ans += m[dx*dx + dy*dy] ++;
			}
		}
		return 2*ans;
    }
};



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