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

Solution: Use HashTable, Time: O(N^2), Space: O(N)

我的:注意14行是有value个重复distance,表示有value个点,他们跟指定点距离都是distance,需要选取2个做permutation, 所以是value * (value-1)

 1 public class Solution {
 2     public int numberOfBoomerangs(int[][] points) {
 3         int res = 0;
 4         for (int i=0; i<points.length; i++) {
 5             HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
 6             for (int j=0; j<points.length; j++) {
 7                 if (i == j) continue;
 8                 int dis = calDistance(points[i], points[j]);
 9                 if (!map.containsKey(dis)) map.put(dis, 1);
10                 else map.put(dis, map.get(dis)+1);
11             }
12             for (int value : map.values()) {
13                 if (value > 1) {
14                     res += value * (value - 1);
15                 }
16             }
17         }
18         return res;
19     }
20     
21     public int calDistance(int[] p1, int[] p2) {
22         int dx = Math.abs(p2[0] - p1[0]);
23         int dy = Math.abs(p2[1] - p1[1]);
24         return dx*dx + dy*dy;
25     }
26 }

 

别人的简洁写法

 1 public int numberOfBoomerangs(int[][] points) {
 2     int res = 0;
 3 
 4     Map<Integer, Integer> map = new HashMap<>();
 5     for(int i=0; i<points.length; i++) {
 6         for(int j=0; j<points.length; j++) {
 7             if(i == j)
 8                 continue;
 9             
10             int d = getDistance(points[i], points[j]);                
11             map.put(d, map.getOrDefault(d, 0) + 1);
12         }
13         
14         for(int val : map.values()) {
15             res += val * (val-1);
16         }            
17         map.clear();
18     }
19     
20     return res;
21 }
22 
23 private int getDistance(int[] a, int[] b) {
24     int dx = a[0] - b[0];
25     int dy = a[1] - b[1];
26     
27     return dx*dx + dy*dy;
28 }

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值