首页 > 代码库 > LeetCode Number of Boomerangs
LeetCode Number of Boomerangs
原题链接在这里: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 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]]
题解:
对于每一个点,求其余所有点到这点的距离. 距离相同的都放在一起, 用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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。