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]]

    链接: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

  • 相关阅读:
    Windows 10 PC 安装 Docker CE
    macOS 安装 Docker
    CentOS 安装 Docker CE
    Debian安装Docker
    ubuntu安装Docker
    docker基本概念
    linux docket
    Express框架
    Koa1 框架
    2018年03月刷题学习日记
  • 原文地址:https://www.cnblogs.com/panini/p/6621957.html
Copyright © 2011-2022 走看看