2022/9/4:哈希表,各种重写的区别

这篇博客介绍了如何使用C++的map数据结构解决LeetCode中关于回旋镖数量的问题。作者首先解释了朴素解法的超时问题,然后提出以一个点为固定点,计算并存储其他点的距离,再利用map遍历找到相同距离的点对,通过组合计算回旋镖的数量。文中提供了两种遍历map的方法,并讨论了C++中的重载、覆盖和重写概念。
摘要由CSDN通过智能技术生成

leetcode:

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

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

朴素的三次循环会超时。将三个点中的一个点作为定点,计算每个点到这个点的距离然后存到哈希表里。在哈希表中,假设距离同为dis的有K个点,考虑元组顺序,从K个点中挑两个点形成回旋镖, m=k*(k-1);

class Solution {
public:
    int numberOfBoomerangs(vector<vector<int>>& points) {
        int n=points.size();
        int num=0,dis1=0,dis2=0;      
        for(int i=0;i<n;i++)
        { map<int,int> m;
            for(int j=0;j<n;j++)
            {  if(i!=j){
                dis1=pow((points[i][0]-points[j][0]),2)+pow((points[i][1]-points[j][1]),2);
                m[dis1]++;
                }
            }
            for(auto& [_1,val]:m)
            {     
            num+=val*(val-1);
            }
        }
          return num;
    }
  
};

之前没有用过map,今天学了一下map的遍历

1.迭代器遍历

#include <map>
#include <iostream>
//...
std::map<int, string> m;
//...
for (auto it = m.begin(); it != m.end(); ++it) {
	//key
	std::cout << it->first << std::endl;
	//value 
	std::cout << it->second << std::endl;
}

2. for遍历

(25条消息) C++之map遍历_活力鲇鱼的博客-CSDN博客_c++ map遍历

C++语法:

overload重载:一些名称相同,参数不同的函数。程序通过判断你传递的参数去找到合适的函数来执行。

override覆盖:多见于派生类继承基类时。名称相同,参数相同。父类的函数带有virtual关键字,子类的方法会覆盖父类的方法来实现多样性。

overwrite重写:派生类函数屏蔽了与其同名的基类函数。参数不同的时候,基类不管有没有virtual关键字都会被隐藏,参数相同的时候,没有关键字基类也会被隐藏。

Overloading occurs when two or more methods in one class have the same method name but different parameters.
Overriding or overwrite means having two methods with the same method name and parameters (i.e., method signature). One of the methods is in the parent class and the other is in the child class.


(26条消息) override、overwrite和overload的区别_MomoForU的博客-CSDN博客

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值