zoukankan      html  css  js  c++  java
  • 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:
    2
    
    Explanation:
    The two boomerangs are [[1,0],[0,0],[2,0]] and [[1,0],[2,0],[0,0]]
    题目含义:定义一种类似“回形标”的三元组结构,即在三元组(i, j, k)中i和j之间的距离与i和k之间的距离相等。找到一组坐标数据中,可构成几组这样的“回形标”结构。
     1     private int getDistance(int[] p1, int[] p2) {
     2         int x = p1[0] - p2[0];
     3         int y = p1[1] - p2[1];
     4         return x * x + y * y;
     5     }
     6     
     7     public int numberOfBoomerangs(int[][] points) {
     8         if (points.length == 0 || points[0].length == 0) return 0;
     9         int result = 0;
    10         for (int i = 0; i < points.length; i++) {
    11             Map<Integer, Integer> distances = new HashMap<>();
    12             for (int j = 0; j < points.length; j++) {
    13                 if (i == j) continue;
    14                 int distance = getDistance(points[i], points[j]);
    15                 distances.put(distance, distances.getOrDefault(distance, 0) + 1);
    16             }
    17             for (Integer count : distances.values()) {
    18                 result += count * (count - 1); //只有大于两条的才能有值.count个节点距离都相等,任选两条就可以与其它边一起构成会回形标。所以可以构成count * (count - 1)条
    19             }
    20         }
    21         return result;     
    22     }
  • 相关阅读:
    面试题 33 把数组排成最小的数
    面试题32 1的数目
    面试题29 数组中出现次数超过一半的数字
    LeetCode_Combination Sum II
    LeetCode_Combination Sum
    面试题27 二叉搜索树转换为双向链表
    面试题26 复杂链表的复制
    面试题24 二叉搜索树的后序遍历序列
    LeetCode_Binary Tree Inorder Traversal
    省选模拟57 题解
  • 原文地址:https://www.cnblogs.com/wzj4858/p/7718710.html
Copyright © 2011-2022 走看看