题目内容:
设计算法找出整数数组a[n](n<=50)中相差最小的两个元素(称为最接近数)的差。
输入格式:
第一行为数组大小n,第二行为n个数组元素,元素之间用空格分开
输出格式:
最接近数的差
输入样例:
5
65 38 26 75 40
输出样例:
2
import java.util.Arrays;
import java.util.Scanner;
/**
* @ClassName Main
* @Description TODO:
* @Author [email protected]
* @Date 2022/5/5 15:11
* @Version 1.0
*/
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int[] nums = new int[n];
for (int i = 0; i < n; i++) {
nums[i] = scan.nextInt();
}
Arrays.sort(nums);
int res = Integer.MAX_VALUE;
for (int i = 1; i < n; i++) {
res = Math.min (res,nums[i] - nums[i-1]);
}
System.out.println(res);
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)