題目:
給你一個整數(shù)數(shù)組 arr 或颊,請你刪除最小 5% 的數(shù)字和最大 5% 的數(shù)字后,剩余數(shù)字的平均值传于。
與 標準答案 誤差在 10-5 的結(jié)果都被視為正確結(jié)果。
示例 1:
輸入:arr = [1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3]
輸出:2.00000
解釋:刪除數(shù)組中最大和最小的元素后醉顽,所有元素都等于 2沼溜,所以平均值為 2 。
示例 2:
輸入:arr = [6,2,7,5,1,2,0,3,10,2,5,0,5,5,0,8,7,6,8,0]
輸出:4.00000
示例 3:
輸入:arr = [6,0,7,0,7,5,7,8,3,4,0,7,8,1,6,8,1,1,2,4,8,1,9,5,4,3,8,5,10,8,6,6,1,0,6,10,8,2,3,4]
輸出:4.77778
示例 4:
輸入:arr = [9,7,8,7,7,8,4,4,6,8,8,7,6,8,8,9,2,6,0,0,1,10,8,6,3,3,5,1,10,9,0,7,10,0,10,4,1,10,6,9,3,6,0,0,2,7,0,6,7,2,9,7,7,3,0,1,6,1,10,3]
輸出:5.27778
示例 5:
輸入:arr = [4,8,4,10,0,7,1,3,7,8,8,3,4,1,6,2,1,1,8,0,9,8,0,3,9,10,3,10,1,10,7,3,2,1,4,9,10,7,6,4,0,8,5,1,2,1,6,2,5,0,7,10,9,10,3,7,10,5,8,5,7,6,7,6,10,9,5,10,5,5,7,2,10,7,7,8,2,0,1,1]
輸出:5.29167
提示:
20 <= arr.length <= 1000
arr.length 是 20 的 倍數(shù)
0 <= arr[i] <= 10^5
來源:力扣(LeetCode)
鏈接:https://leetcode.cn/problems/mean-of-array-after-removing-some-elements
著作權歸領扣網(wǎng)絡所有游添。商業(yè)轉(zhuǎn)載請聯(lián)系官方授權系草,非商業(yè)轉(zhuǎn)載請注明出處。
思路:
先將數(shù)組排序唆涝,然后去除最前面的1/20和最后面的1/20, 計算剩余元素的開始下標和結(jié)束下標找都,得到剩余元素的個數(shù),然后計算剩余元素之和除以剩余元素個數(shù)的結(jié)果廊酣,即為剩余數(shù)字的平均值能耻。
java代碼:
class Solution {
public double trimMean(int[] arr) {
Arrays.sort(arr);
int length = arr.length;
int start = length / 20, end = length - length / 20 - 1;
int remain = end - start + 1;
double sum = 0;
for (int i = start; i <= end; i++) {
sum += arr[i];
}
return sum / remain;
}
}