题目描述
中位数
进阶
- 星星还是树 【https://www.acwing.com/problem/content/3170/】
时间复杂度
参考文献
JAVA 代码
import java.util.*;
import java.io.*;
public class Main{
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
String[] str = br.readLine().split(" ");
int[] a = new int[n];
for(int i=0; i<n; i++){
a[i] = Integer.parseInt(str[i]);
}
Arrays.sort(a);
int res = 0;
for(int i=0; i<n; i++){
res += a[i] - a[i/2];
}
System.out.println(res);
}
}
JAVA 代码2
import java.util.*;
import java.io.*;
public class Main{
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
String[] str = br.readLine().split(" ");
int[] a = new int[n];
for(int i=0; i<n; i++){
a[i] = Integer.parseInt(str[i]);
}
Arrays.sort(a);
int res = 0;
for(int i=0; i<n; i++){
res +=Math.abs(a[i] - a[n/2]);
}
System.out.println(res);
}
}
JAVA 代码3
import java.util.*;
public class Main
{
static Scanner in = new Scanner(System.in);
static int N = 100010;
static int a[] = new int[N];
public static void main(String args[])
{
int n = in.nextInt();
for (int i = 0; i < n; i++) a[i] = in.nextInt();
Arrays.sort(a, 0, n);
int ans = 0;
for (int i = 0; i < n; i++) ans += Math.abs(a[i] - a[n / 2]);
System.out.println(ans);
}
}