AB数对 码蹄集

题目来源:码蹄集

题目描述:

在这里插入图片描述
在这里插入图片描述

大致思路:

  1. 遍历输入的n个整数,将每个数存入哈希表中,key为数值,value为该数出现的次数。

  2. 再次遍历这n个整数,对于每个数x,计算出x-C和x+C的值,然后在哈希表中查找是否存在这两个数。

Python代码实现:

p = 1000003 
h = [None] * p

def hash_func(a):
    return a % p 

def findd(x):
    y = hash_func(abs(x))
    while h[y] and h[y][0] != x:
        y = hash_func(y + 1)  
    return y

def push(x):
    y = findd(x) 
    if h[y] is None:
        h[y] = [x, 1] 
    else:
        h[y][1] += 1

def check(x):
    y = findd(x)  
    if h[y] is None:
        return 0
    else:
        return h[y][1]

n, m = map(int, input().split())
a = list(map(int, input().split()))
for i in range(n):
    push(a[i])
ans = 0
for i in range(n):
    ans += check(a[i] - m) 
print(ans)

C++代码实现:

参考链接:https://blog.csdn.net/CCCCDEV_CCCC/article/details/116106680

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#define p 1000003//这就是我们需要取余的数
#define hash(a) a%p//hash函数 
using namespace std;
long long n,m,a[p],ans;
struct node{
	long long x;//这个位置对应的数 
	int y;//次数 
}h[p];
int findd(long long x)
{//hash关键字,避免冲突的 
	int y=hash(abs(x));//获取hash值 
	while(h[y].x&&h[y].x!=x) y=hash(++y);
	//避免冲突,往一个存 
	return y; 
}
void push(long long x)
{//映射散列表 
	int y=findd(x);
	h[y].y++;
	h[y].x=x;
	//存储再散列表中然后次数加一 
 }
 int check(long long x)
 {//统计次数 
 	return h[findd(x)].y;
 }
int main()
{
	cin>>n>>m;
	for(long long i=1;i<=n;i++)
		cin>>a[i],push(a[i]);
	for(long long i=1;i<=n;i++)
		ans+=check(a[i]-m);//统计出现次数 
	cout<<ans<<endl;
	return 0;
}

代码提交测试结果:

在这里插入图片描述
附B站老师思路讲解:https://www.bilibili.com/video/BV1Ua4y1V7qX/?t=1305.3

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Magneto_万磁王

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值