首页 > 其他 > 详细

LeetCode Number of Boomerangs

时间:2017-01-31 10:35:26      阅读:401      评论:0      收藏:0      [点我收藏+]

原题链接在这里:https://leetcode.com/problems/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 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]]

题解:

对于每一个点,求其余所有点到这点的距离. 距离相同的都放在一起, 用HashMap<Integer, Integer> hm保存. key是distance, value是相同distance的点的个数.

对于这一点不同的组合方法有value * (value-1)种.

每个点的组合方法都加到res中return.

Time COmplexity: O(n^2), n = points.length. Space: O(n).

AC Java:

 1 public class Solution {
 2     public int numberOfBoomerangs(int[][] points) {
 3         if(points == null || points.length == 0){
 4             return 0;
 5         }
 6         
 7         int res = 0;
 8         HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();
 9         for(int i = 0; i<points.length; i++){
10             for(int j = 0; j<points.length; j++){
11                 if(i == j){
12                     continue;
13                 }
14                 
15                 int dist = getDistance(points[i], points[j]);
16                 hm.put(dist, hm.getOrDefault(dist, 0)+1);
17             }
18             
19             for(int val : hm.values()){
20                 res += val * (val-1);
21             }
22             hm.clear();
23         }
24         
25         return res;
26     }
27     
28     private int getDistance(int [] p, int [] q){
29         int dx = p[0] - q[0];
30         int dy = p[1] - q[1];
31         return dx*dx + dy*dy;
32     }
33 }

 

LeetCode Number of Boomerangs

原文:http://www.cnblogs.com/Dylan-Java-NYC/p/6358640.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!