P1102 A-B 数对
题目
思路
这道题可以用到hashmap集合来搞定,haspmap里主键就放数字,值就放他有多少个主键,就比如1 1 1 2 2 2,那么那就会显示1有3个1 2有3个2,然后A-B=C可以变成A-C=B,我们遍历一遍过去,判断hash里面是否有B这个值,如果有的话,就直接加上B键的值(提醒:统计要用到long,int会超过)
代码
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
public class AB {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int c = in.nextInt();
Map<Integer, Integer> map = new HashMap<>();
int[] arra = new int[n];
for (int i = 0; i < arra.length; i++) {
arra[i] = in.nextInt();
if (map.containsKey(arra[i])) {
int a = map.get(arra[i]);
map.put(arra[i], a + 1);
} else {
map.put(arra[i], 1);
}
}
long count = 0;
for (int i = 0; i < n; i++) {
int dff = arra[i] - c;
if (map.containsKey(dff)) {
int a = map.get(dff);
if (a > 0) {
count += a;
}
}
}
System.out.println(count);
// Set<Integer> key = map.keySet();
// for (Integer a : key) {
// System.out.println(a + " " + map.get(a));
// }
}
}
空空如也!