sakura、 @ 2022-04-01 21:25:22
以下为代码,实在找不到哪里有错,测试样例又下载不了
import java.util.Arrays;
import java.util.Scanner;
public class Main {
static int m, n, sum;
static int[] school = new int[100000];
static int[] score = new int[100000];
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
m = sc.nextInt();
n = sc.nextInt();
for (int i = 0; i < m; i++) {
school[i] = sc.nextInt();
}
Arrays.sort(school, 0, m);
for (int i = 0; i < n; i++) {
score[i] = sc.nextInt();
sum += find(score[i]);
}
System.out.println(sum);
}
static int find(int num) {
int l = 0, r = n - 1;
int min = Integer.MAX_VALUE;
while (l <= r) {
int mid = (l + r) / 2;
if (school[mid] == num) {
return 0;
}//当前值正好等于num,直接返回0
else if (school[mid] > num) {
min = Math.min(min, Math.abs(school[mid] - num));
r = mid - 1;
}//收缩边界同时获得最小值
else if(school[mid] < num) {
min = Math.min(min, Math.abs(school[mid] - num));
l = mid + 1;
}
}
return min;//返回最小值
}
}
by w23c3c3 @ 2022-04-01 21:33:53
是不是 n,m 反了。
by Usada_Pekora @ 2022-04-01 21:52:28
@sakura、 find要在
by sakura、 @ 2022-04-01 22:39:31
@w23c3c3 还真是,改了就ac了....谢谢好哥哥提醒,居然犯了这么蠢的错....还是太菜了
by sakura、 @ 2022-04-01 22:40:11
@Zyingyzzz 是的是的,改了就好了....谢谢好哥哥