Java Huawei Real Exam Questions-New School Site Selection

need:

  In order to solve the problem of the skyrocketing number of students in the new semester, Xiaole Village needs to build a new school. Considering the safety of students going to school, the distance from all students' homes to the school needs to be the shortest. Assuming that the school and all students' homes are in a straight line, where should the school be built to minimize the distance from the school to each student's home?

Enter description:

    The first line: The value range of integer n is [1,1000], indicating that there are n households.

    The second line: a set of integers m in the value range [0,10000], indicating the location of each household, and the locations of all households are different.

Output description:

    An integer that determines the location of the school. If there are multiple locations, the smallest one is output.

 

enter

5

0 20 40 10 30

output

20

 

coding:

public class AddressNew {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("输入用户:");
        int n = sc.nextInt();
        sc.nextLine(); // 这里使用nextLine()来接收上面的'\n'
        System.out.print("输入" + n + "个所有家庭位置:");
        String[] strs = sc.nextLine().split(" ");
        //字符串数组转换成整数数组
        int[] arr = Arrays.asList(strs).stream().mapToInt(Integer::parseInt).toArray();
        //(1)排序
        Arrays.sort(arr);
        System.out.println("排序后数据:"+Arrays.toString(arr));
        //(2)最小距离(求中位数)
        int min = 0;

        //判断是偶数还是奇数,
        if (n % 2 == 0) {
            min = arr[n / 2 - 1];
        } else {
            min = arr[n/2];
        }
        System.out.println("最小距离:" + min);
    }

}

Effect:

Guess you like

Origin blog.csdn.net/hlx20080808/article/details/132855264