Loading...

BISHI24 谐距下标对

在这里插入图片描述

求解代码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
public static void main(String[] args) throws IOException {

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        StreamTokenizer in = new StreamTokenizer(br);

        PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));

        in.nextToken();
        int n = (int) in.nval;

        // 创建HashMap:键=差值diff(Integer),值=该diff出现的次数(Integer)
        Map<Integer, Integer> hMap = new HashMap<>();

        for (int i = 0; i < n; i++) {
            in.nextToken();
            int a = (int) in.nval;

            // diff = 前整数 - 它的位置索引
            int diff = a - i;
            hMap.put(diff, hMap.getOrDefault(diff, 0) + 1);
        }
        long total = 0;

        // 遍历Map中所有diff的出现次数
        for (int count : hMap.values()) {
            // 只有出现次数>1的diff,才能组成数对(至少2个元素才能配对)
            if (count > 1) {
                // 相同 diff 的数,两两之间都满足题目要求的条件,
                // 所以统计每个 diff 的出现次数,再算组合数就是答案。
                total += (long) count * (count - 1) / 2;
            }
        }

        out.println(total);

        out.flush();
        out.close();
        br.close();
    }

小贴士

$a_j -a_i = j-i$➡️$a_j - j= a_i-i$

最后更新于 2026-04-05 17:35:33
Code Road Record