• 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 }

     

  • 相关阅读:
    TDD
    算法与数据结构 文档 1 洋洋洋传
    编程的专精度
    python小课
    有时心情舒畅时打个代码心里都是默默地同步输出...
    同时可以运行在JVM上的Kotlin~枚举和判定以及数据对象的写法总结
    map
    multiset
    set
    priority_queue
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/6140918.html
Copyright © 2020-2023  润新知