447. 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: 2Explanation: The two boomerangs are [[1,0],[0,0],[2,0]] and [[1,0],[2,0],[0,0]]鏈接:https://leetcode.com/problems/number-of-boomerangs/#/description
3/25/2017
自己的算法超時了,看別人答案
然而,基本上除了計算距離之外,不需要記錄很多,因為本身答案需要的也就是數量而不是index
有時候需要想一想有沒有簡單的方法,想不到再硬來。
https://discuss.leetcode.com/topic/66587/clean-java-solution-o-n-2-166ms/2
回憶著這個答案,還是錯了,真正理解了一下:
注意加count和map.clear()是在每個i里都進行的。為什么?當有從一個頂點開始相同的距離時,這個頂點就是i為index的點。而另外一個點就是相同距離里的其他點,用排列數計算。
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 }更多討論:
https://discuss.leetcode.com/category/574/number-of-boomerangs
轉載于:https://www.cnblogs.com/panini/p/6621957.html
總結
以上是生活随笔為你收集整理的447. Number of Boomerangs的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 改变网页标签图片(favicon)
- 下一篇: LoadRunner11支持的浏览器小结