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

    Problem:

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

    Summary:

    定义一种类似“回形标”的三元组结构,即在三元组(i, j, k)中i和j之间的距离与i和k之间的距离相等。找到一组坐标数据中,可构成几组这样的“回形标”结构。

    Analysis:

    若在一组点集{a, b, c, d, ...}中,以点a为一个端点,与dis(a, b)相等的点存在n个(包含点b),那么在这n个点中任意选出两个点与点a构成三元组,则有n(n - 1) / 2种情况。但因为三元组[a, b, c]与三元组[a, c, b]并不相同,所以实际为排列问题,答案为n(n - 1)。

    代码中正是以此为基本思想,找到以每一个点为端点时,与其余点共组成多少种不同的距离,此处用map记录,key为距离长度,value为距离出现次数。再根据前面的公式计算即可。

     1 class Solution {
     2 public:
     3     int numberOfBoomerangs(vector<pair<int, int>>& points) {
     4         int len = points.size(), res = 0;
     5         unordered_map<int, int> m;
     6         
     7         for (int i = 0; i < len; i++) {
     8             for (int j = 0; j < len; j++) {
     9                 int x = points[i].first - points[j].first;
    10                 int y = points[i].second - points[j].second;
    11                 m[x * x + y * y]++;
    12             }
    13             
    14             unordered_map<int, int> :: iterator it;
    15             for (it = m.begin(); it != m.end(); it++) {
    16                 int tmp = it->second;
    17                 res += tmp * (tmp - 1);
    18             }
    19             m.clear();
    20         }
    21         
    22         return res;
    23     }
    24 };
  • 相关阅读:
    iOS的流畅性
    iOS系统的特点-iOS为什么运行更流畅
    安卓怎么不如ios运行流畅
    关于后台动态模板添加内容的总结 Builder使用
    PHP中用下划线开头的变量含义
    php 变量名前加一个下划线含义
    ThinkPHP 模版中的内置标签
    PC端页面如何调用QQ进行在线聊天?
    手机web页面调用手机QQ实现在线聊天的效果
    THINKPHP框架的优秀开源系统推荐
  • 原文地址:https://www.cnblogs.com/VickyWang/p/6065236.html
Copyright © 2011-2022 走看看