为了解新学期学生暴涨的问题,小乐村要建立所新学校,考虑到学生上学安全问题,需要所有学生家到学校的距离最短。
假设学校和所有学生家都走在一条直线之上,请问学校建立在什么位置,能使得到学校到各个学生家的距离和最短。
输入描述:
第一行: 整数 n 取值范围 [1, 1000],表示有n户家庭。
第二行: 一组整数 m 取值范围 [0, 10000] ,表示每户家庭的位置,所有家庭的位置都不相同。
输出描述:一个整数,确定的学校的位置。如果有多个位置,则输出最小的。
暴力
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int number = sc.nextInt();
int[] people = new int[number];
for(int i = 0;i < number;i++){
people[i] = sc.nextInt();
}
//number取多少时 number坐标的差
int[][] dp = new int[number][number];
//计算每个坐标距离
for(int i = 0;i < number;i++){
for(int j = 0;j < number;j++){
dp[i][j] = Math.abs(people[i] - people[j]);
}
}
int min = Integer.MAX_VALUE;
int res = 0;
for(int i = 0;i < number;i++){
int tempMin = 0;
for(int j = 0;j < number;j++){
tempMin += dp[i][j];
}
if(min > tempMin){
res = people[i];
min = tempMin;
}else if(tempMin == min){
res = Math.min(res,people[i]);
}
}
System.out.print(res);
}
}
选中位数
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int number = sc.nextInt();
int[] people = new int[number];
for(int i = 0;i < number;i++){
people[i] = sc.nextInt();
}
// 对数组进行排序
Arrays.sort(people);
// 对数组排好序
// 若n为奇数,则为 people[n / 2],就中位数,中间一定到两边最小
// 若n为偶数,则为 people[n / 2 - 1],选靠左的元素,省略中间两个点,其它点的距离都是固定长度,中间相向,同时又是输出最小的
if(number % 2 != 0){
//5选第三个位置,索引2
System.out.println(people[number / 2]);
}else{
//5选第二个位置,索引1
System.out.println(people[number / 2 - 1]);
}
}
}