中位数还是中间数
正确解法 中位数 原理y总已经证明
#include<bits/stdc++.h>
using namespace std;
int n, a[100100];
int jdz(int x, int y) {
if(x < y) return y - x;
else return x - y;
}
int main() {
cin >> n;
for(int i = 0; i < n; i++) cin >> a[i];
sort(a, a + n);
int s = 0;
for(int i = 0; i < n; i++) {
s += jdz(a[i], a[n / 2]);
}
cout << s;
return 0;
}
错误解法 中间数
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll a[100100];
ll jdz(ll x, ll y) {
if(x < y) return y - x;
else return x - y;
}
int main() {
int n;
cin >> n;
ll mi = 9220000000000000, mx = 0;
for(int i = 1; i <= n; i++) {
scanf("%lld", &a[i]);
if(a[i] < mi) mi = a[i];
if(a[i] > mx) mx = a[i];
}
ll s = 0;
for(int j = 1; j <= n; j++) {
s += jdz(a[j], (mi + mx) / 2);
}
cout << s;
return 0;
}
为啥中间数不行,如 1 6 8 9 四个数, [1, 9] 中间数是 5, 而5并没有落在[6, 8]之间。但如果是中位数,不管是6,还是8 都会落在区间[1, 9] 和 [6, 8]之间的。(落在端点也没关系)