7-3 相邻数对 (20 分)java版

给定n个不同的整数,问这些数中有多少对整数,它们的值正好相差1。

输入格式:
输入的第一行包含一个整数n,表示给定整数的个数。 第二行包含所给定的n个整数。

输出格式:
输出一个整数,表示值正好相差1的数对的个数。

输入样例:

6
10 2 6 3 7 8

输出样例:

3

样例说明:
值正好相差1的数对包括(2, 3), (6, 7), (7, 8)。

评测用例规模与约定:
1<=n<=1000,给定的整数为不超过10000的非负整数。

import java.util.*;

public class Main {

    public static void main(String[] args) {
        int result = 0;
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] sz = new int[n];
        HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();
        for (int i = 0; i < n; i++) {
            int x = sc.nextInt();
            sz[i] = x;
            if (hm.keySet().contains(x)) {
                hm.put(x, hm.get(x) + 1);
            } else {
                hm.put(x, 1);
            }
        }
        for (int x : sz) {
            if (hm.keySet().contains(x + 1)) {
                result += (hm.get(x + 1));
            }
            if (hm.keySet().contains(x - 1)) {
                result += (hm.get(x - 1));
            }
        }
        System.out.println(result / 2);
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值