由于数字各不相同,如果存在相反数,那么他们的绝对值相等。使用一个数组统计次数,看看记录绝对值的次数,为2就统计一次。
import java.util.*;
public class Main{
private static int N = 1010;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int[] arr = new int[N];
int res = 0;
for (int i = 0; i < n; i++) {
if (++arr[Math.abs(input.nextInt())] >= 2) {
res++;
}
}
System.out.println(res);
input.close();
}
}
本文介绍了一种使用数组来统计一组整数中相反数对的方法。通过遍历输入的整数,利用数组记录每个数的绝对值出现的次数,当某绝对值出现两次时,则认为存在一对相反数。
442

被折叠的 条评论
为什么被折叠?



