牛客网公司真题(笔试)系列
2024/3/23
美团2021校招笔试-编程题(通用编程试题,第10场)
import java.util.Scanner;
import java.util.Arrays;
import java.lang.Math;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
int n = in.nextInt();
int[] nums = new int[n];
for(int i = 0; i < n; i++){
nums[i] = in.nextInt();
}
int result = test(n, nums);
System.out.println(result);
}
//思路:先将数组排序,然后将其与[1,2,...,n]数组一一比对
public static int test(int n, int[] nums){
Arrays.sort(nums);
int c = 0; //变动次数
for(int i = 0; i < n; i++){
c += Math.abs(nums[i]-(i+1));
}
return c;
}
}
总结:
acm模式最好记得,Math工具是在 java.lang 包下