CCF系列之相邻数对(201409-1)

试题编号: 201409-1

时间限制: 1.0s 
内存限制: 256.0MB

问题描述
  给定n个不同的整数,问这些数中有多少对整数,它们的值正好相差1。
输入格式
  输入的第一行包含一个整数n,表示给定整数的个数。   第二行包含所给定的n个整数。
输出格式
  输出一个整数,表示值正好相差1的数对的个数。
样例输入
6
10 2 6 3 7 8
样例输出
3
样例说明
  值正好相差1的数对包括(2, 3), (6, 7), (7, 8)。
评测用例规模与约定
  1<=n<=1000,给定的整数为不超过10000的非负整数。

解题思路:

代码(java):

  

 1 package ccf_test2014_09;
 2 
 3 import java.util.Scanner;
 4 
 5 public class XianglinShudu {
 6     
 7 
 8     public static void main(String[] args) {
 9         
10          int result = 0;
11          
12          int cha = 0;
13          
14          Scanner input = new Scanner(System.in);
15          
16          int num = input.nextInt();
17          
18          input.nextLine();
19          
20          int[]shulie = new int[num];
21          
22          for(int i = 0; i < shulie.length; i++){
23              
24              shulie[i] = input.nextInt();
25          }
26          
27         for(int i = 0; i < shulie.length - 1; i++){
28             
29             for(int j = i + 1; j < shulie.length; j++){
30                 
31                 cha = shulie[i] - shulie[j];
32                 
33                 if(Math.abs(cha) ==1 ){
34                     
35                     result++;
36                 }
37             }
38         }
39         System.out.println(result);
40         
41     }
42 
43 }

结果:

  

原文地址:https://www.cnblogs.com/haimishasha/p/5329692.html