LeetCode 1619. Mean of Array After Removing Some Elements
考点 | 难度 |
---|---|
Sorting | Easy |
题目
Given an integer array arr
, return the mean of the remaining integers after removing the smallest 5% and the largest 5% of the elements.
Answers within 10-5 of the actual answer will be considered accepted.
思路
先算arr
里所有数的和,再减去前5%和5%,最后除以remove后的长度。
答案
public double trimMean(int[] arr) {
Arrays.sort(arr);
int length = arr.length;
int toRemove = length * 5 / 100;
int total = 0;
for (int number: arr) {
total += number;
}
for (int i=0; i<toRemove; i++)
total -= arr[i];
for (int i=length-1; i>= length-toRemove; i--)
total -= arr[i];
length -= (2 * toRemove);
return (double) ((double)total / (double)length);
}