有n个数,两两组成二元组,差最小的有多少对呢?差最大呢?
以下为我的解答
package com.ikok;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class FunnyNumber {
// 最小最大差值的对数
static int minNum = 0;
static int maxNum = 0;
// 最小最大的差值
static int minDValue = 0;
static int maxDValue = 0;
// 数组元素的个数
static int n = 0;
// 输入的数组
static List<Integer> datas = new ArrayList<Integer>();
public static void main(String[] args) {
getNumberArray();
getResult();
}
/**
* 得到结果
*/
private static void getResult() {
// 得到前两个数的差值,用前两个数字的差值初始化最小与最大差值
int firstDValue = datas.get(0) - datas.get(1);
if (firstDValue >= 0) {
maxDValue = firstDValue;
minDValue = firstDValue;
} else {
maxDValue = -firstDValue;
minDValue = -firstDValue;
}
for (int i = 0; i < datas.size(); i++) {
for (int j = i + 1; j < datas.size(); j++) {
// 临时差值
int tempDValue = 0;
if (datas.get(i) >= datas.get(j)) {
tempDValue = datas.get(i) - datas.get(j);
} else {
tempDValue = datas.get(j) - datas.get(i);
}
// 如果差值比最大差值大,则修改最大差值,同时最大差值对数变为1
// 如果差值和最大差值相等,则最大差值对数加1
if (tempDValue > maxDValue) {
maxDValue = tempDValue;
maxNum = 1;
} else if(tempDValue == maxDValue) {
maxNum++;
}
// 如果差值比最小差值小,则修改最小差值,同时最小差值对数变为1
// 如果差值和最小差值相等,则最小差值对数加1
if (tempDValue < minDValue) {
minDValue = tempDValue;
minNum = 1;
} else if(tempDValue == minDValue) {
minNum++;
}
}
}
System.out.println("最小差值对数 " + minNum);
System.out.println("最大差值对数 " + maxNum);
// System.out.println("最大差值 " + maxDValue);
// System.out.println("最小差值 " + minDValue);
}
/**
* 得到数组
*/
private static void getNumberArray() {
Scanner scanner = new Scanner(System.in);
n = scanner.nextInt();
for (int i = 0; i < n; i++) {
int tempNum = 0;
tempNum = scanner.nextInt();
datas.add(tempNum);
}
}
}