zoukankan      html  css  js  c++  java
  • 447. Number of Boomerangs(LeetCode)

    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 andj 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]]
     1 int numberOfBoomerangs(vector<pair<int, int>>& points) {
     2     
     3     int res = 0;
     4     
     5     // iterate over all the points
     6     for (int i = 0; i < points.size(); ++i) {
     7         
     8         unordered_map<long, int> group(points.size());
     9         
    10         // iterate over all points other than points[i]
    11         for (int j = 0; j < points.size(); ++j) {
    12             
    13             if (j == i) continue;
    14             
    15             int dy = points[i].second - points[j].second;
    16             int dx = points[i].first - points[j].first;
    17             
    18             // compute squared euclidean distance from points[i]
    19             int key = dy * dy;
    20             key += dx * dx;
    21             
    22             // accumulate # of such "j"s that are "key" distance from "i"
    23             ++group[key];
    24         }
    25         
    26         for (auto& p : group) {
    27             if (p.second > 1) {
    28                 /*
    29                  * for all the groups of points, 
    30                  * number of ways to select 2 from n = 
    31                  * nP2 = n!/(n - 2)! = n * (n - 1)
    32                  */
    33                 res += p.second * (p.second - 1);
    34             }
    35         }
    36     }
    37     
    38     return res;
    39 }
    int numberOfBoomerangs(vector<pair<int, int>>& points) {
        int booms = 0;
        for (auto &p : points) {
            unordered_map<double, int> ctr(points.size());
            for (auto &q : points)
                booms += 2 * ctr[hypot(p.first - q.first, p.second - q.second)]++;
        }
        return booms;
    }
  • 相关阅读:
    redis
    java基础知识起步
    SQL(DML)语法
    jsp中的九大内置对象和四大作用域
    JDBC与javaBean
    javaScript知识点大全
    mysql数据库操作语法大全
    css前端知识点总结
    HTML前端小结
    代码整洁之道
  • 原文地址:https://www.cnblogs.com/wujufengyun/p/6839144.html
Copyright © 2011-2022 走看看