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:2Explanation: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; imap = new HashMap (); 6 for (int j=0; j 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 Mapmap = new HashMap<>(); 5 for(int i=0; i