問題描述: |
問題描述 給定n個不同的整數,問這些數中有多少對整數,它們的值正好相差1。 輸入格式 輸入的第一行包含一個整數n,表示給定整數的個數。 輸出格式 輸出一個整數,表示值正好相差1的數對的個數。 樣例輸入 6 樣例輸出 3 樣例說明 值正好相差1的數對包括(2, 3), (6, 7), (7, 8)。 評測用例規模與約定 1<=n<=1000,給定的整數爲不超過10000的非負整數。 |
package adjacentPairs;
import java.util.Scanner;
public class Main {
@SuppressWarnings("resource")
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();// 記錄整數個數
int[] arr = new int[n];// 存放所有整數
int result = 0;// 符合題意的結果數目
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
for (int i = 0; i < n - 1; i++)// 將第i個整數與後面的整數作差,絕對值爲1則result遞增
{
for (int t = i + 1; t < n; t++) {
if (Math.abs(arr[i] - arr[t]) == 1)
result++;
}
}
System.out.println(result);
}
}