LeetCode-Easy部分标签为HashTable 447. Number of Boomerangs
来源:互联网 发布:淘宝页头尺寸 编辑:程序博客网 时间:2024/05/15 06:51
原题
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:2Explanation:The two boomerangs are [[1,0],[0,0],[2,0]] and [[1,0],[2,0],[0,0]]
题目分析
给出n组点,找出所有boomerang
的个数,boomerang
定义: d(Pi,Pj)=d(Pi,Pk)
。题目涉及到三个点,先保持一个轴点rot
,然后找与其他点的距离,若个数为m,m满足m>1
,则找到轴点rot
的Boomerangs 个数为A(m,2)
,继续遍历其他轴点,返回累加和。
代码分析
public static int NumberOfBoomerangs(int[,] points) { Dictionary<double, int> dict = new Dictionary<double, int>(); int len = points.GetUpperBound(0); int rtnCnt=0; for (int i = 0; i <= len; i++) { //3点变2点 for (int j = 0; j <= len; j++) { if (i == j) continue; double d = distance(points[i, 0], points[j, 0], points[i, 1], points[j, 1]); if (dict.ContainsKey(d)) dict[d]++; else dict.Add(d, 1); } foreach(var item in dict) { if (item.Value > 1) { //如果找到了value个,因为有顺序,所以排序 rtnCnt += item.Value*(item.Value-1); } } dict.Clear(); } return rtnCnt; } private static double distance(int x1, int x2, int y1, int y2) { int x = x1 - x2; int y = y1 - y2; return Math.Sqrt(x * x + y * y); }
结果分析
算法运行时间为 Runtime: 372 ms
,排名85%
。
时间复杂度O(n^2),控件复杂度O(n)。
更多参考
LeetCode-Easy部分中标签为HashTable的所有题目
1 0
- LeetCode-Easy部分标签为HashTable 447. Number of Boomerangs
- LeetCode-Easy部分标签为HashTable#136 Single Number
- LeetCode 447. Number of Boomerangs
- leetcode:447. Number of Boomerangs
- leetcode 447. Number of Boomerangs
- LeetCode 447. Number of Boomerangs
- 【LeetCode】 447. Number of Boomerangs
- [LeetCode]447. Number of Boomerangs
- [leetcode] 447. Number of Boomerangs
- Leetcode 447. Number of Boomerangs
- LeetCode 447. Number of Boomerangs
- Leetcode-447. Number of Boomerangs
- [LeetCode]447. Number of Boomerangs
- 【Leetcode】447. Number of Boomerangs
- leetcode 447. Number of Boomerangs
- [leetcode]: 447. Number of Boomerangs
- [LeetCode] 447. Number of Boomerangs
- [LeetCode]447.Number of Boomerangs
- 40个比较重要的Android面试题
- C语言大数运算-加法篇
- hdu 2188(巴什博弈)
- 图像处理算法之图像暗角特效
- 链表实现的散列表(Java版)
- LeetCode-Easy部分标签为HashTable 447. Number of Boomerangs
- Android与JS交互
- Android进阶知识点(隐式Intent,Assets,样式和主题)
- Android6.0的动态权限的简单使用
- Http和Https的区别
- 红牌
- ElasticSearch文档简介
- K叉哈夫曼树
- 蓝桥 快速排序