当前位置: 首页 > news >正文

LeetCode 0447.回旋镖的数量:哈希表

【LetMeFly】447.回旋镖的数量:哈希表

力扣题目链接:https://leetcode.cn/problems/number-of-boomerangs/

给定平面上 n 互不相同 的点 points ,其中 points[i] = [xi, yi]回旋镖 是由点 (i, j, k) 表示的元组 ,其中 i 和 j 之间的距离和 i 和 k 之间的欧式距离相等(需要考虑元组的顺序)。

返回平面上所有回旋镖的数量。

 

示例 1:

输入:points = [[0,0],[1,0],[2,0]]
输出:2
解释:两个回旋镖为 [[1,0],[0,0],[2,0]][[1,0],[2,0],[0,0]]

示例 2:

输入:points = [[1,1],[2,2],[3,3]]
输出:2

示例 3:

输入:points = [[1,1]]
输出:0

 

提示:

  • n == points.length
  • 1 <= n <= 500
  • points[i].length == 2
  • -104 <= xi, yi <= 104
  • 所有点都 互不相同

方法一:哈希表

第一重循环枚举每个 j j j点。对于points[j],使用一个哈希表,记录所有的点到j点的距离的出现次数。然后遍历哈希表,假设某距离出现了cnt次,那么就将 c n t × ( c n t − 1 ) cnt\times(cnt-1) cnt×(cnt1)累加到答案中。

  • 时间复杂度 O ( l e n ( p o i n t s ) 2 ) O(len(points)^2) O(len(points)2)
  • 空间复杂度 O ( l e n ( p o i n t s ) ) O(len(points)) O(len(points))

AC代码

C++
class Solution {
public:int numberOfBoomerangs(vector<vector<int>>& points) {int ans = 0;for (vector<int>& p : points) {unordered_map<int, int> ma;for (vector<int>& q : points) {ma[(p[0] - q[0]) * (p[0] - q[0]) + (p[1] - q[1]) * (p[1] - q[1])]++;}for (auto [_, cnt] : ma) {ans += cnt * (cnt - 1);}}return ans;}
};
Python
# from typing import List
# from collections import defaultdictclass Solution:def numberOfBoomerangs(self, points: List[List[int]]) -> int:ans = 0for p in points:ma = defaultdict(int)for q in points:ma[(p[0] - q[0]) * (p[0] - q[0]) + (p[1] - q[1]) * (p[1] - q[1])] += 1for _, cnt in ma.items():ans += cnt * (cnt - 1)return ans

同步发文于CSDN,原创不易,转载经作者同意后请附上原文链接哦~
Tisfy:https://letmefly.blog.csdn.net/article/details/135464460

http://www.lryc.cn/news/276001.html

相关文章:

  • 容器相关笔记
  • cissp 第10章 : 物理安全要求
  • 聊一聊 .NET高级调试 内核模式堆泄露
  • 海外代理IP在游戏中有什么作用?
  • 高防ip适合防御网站和游戏类的攻击吗?
  • HTML5和JS实现明媚月色效果
  • Django5+DRF序列化
  • 什么是编译程序和解释程序
  • 文档审阅批注的合并和对比
  • 广义零样本学习综述的笔记
  • java每日一题——输出9x9乘法表(答案及编程思路)
  • Android 车联网——基础简介(一)
  • 自动驾驶货车编队行驶系统功能规范
  • javafx
  • 玩转贝启科技BQ3588C开源鸿蒙系统开发板 —— 编译构建及此过程中的踩坑填坑(3)
  • SQL ORDER BY 关键字
  • 多线程-生产者消费者模型
  • 解压命令之一 gzip
  • 力扣:438. 找到字符串中所有字母异位词 题解
  • QT 高DPI解决方案
  • SLB、DMZ、Nginx、Ingress、Gateway、Kibana和Grafana
  • 【已解决】Invalid bound statement (not found)
  • 汽车信息安全--芯片厂、OEM安全启动汇总(1)
  • 气膜建筑:舒适、智能、可持续
  • 【C语言】一种状态超时阻塞循环查询的办法
  • 【leetcode】力扣热门之回文链表【简单难度】
  • 【MySQL】ALL函数的巧用 以及 排序(order by)巧用 sum(条件表达式) 语法
  • Debezium发布历史49
  • 数据结构——队列(Queue)
  • uniapp微信小程序投票系统实战 (SpringBoot2+vue3.2+element plus ) -后端架构搭建