题目背景
出题是一件痛苦的事情!
相同的题目看多了也会有审美疲劳,于是我舍弃了大家所熟悉的 A+B Problem,改用 A-B 了哈哈!
题目描述
给出一串正整数数列以及一个正整数 𝐶C,要求计算出所有满足 𝐴−𝐵=𝐶 的数对的个数(不同位置的数字一样的数对算不同的数对)。
输入格式
输入共两行。
第一行,两个正整数 𝑁,𝐶。
第二行,𝑁 个正整数,作为要求处理的那串数。
输出格式
一行,表示该串正整数中包含的满足 𝐴−𝐵=𝐶 的数对的个数。
代码:
package lanqiao;
import java.util.*;
public class Main{
static int[] a;
static long ans=0;
static int t = 0;//引入变量t,记录键(数字)的次数
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n=in.nextInt();
int c=in.nextInt();
//建立一个数字到出现次数的映射 map<num,times>
Map<Integer,Integer> m=new HashMap<Integer, Integer>();
a=new int[n];
for(int i=0;i<n;i++) {
a[i]=in.nextInt();
if(m.get(a[i])==null)t=0;//必须判断值是否为空,否则报错
else t=m.get(a[i]);
m.put(a[i],++t);
}
//将查找A、B满足A-B=C,转换成只需查找A满足A=B+C
for(int i=0;i<n;i++) {
if(m.get(a[i]+c)!=null)//必须判断值是否为空,否则报错
ans+=m.get(a[i]+c);
}
System.out.println(ans);
}
}