Given an integer array
arr
, return the mean of the remaining integers after removing the smallest 5%
and the largest 5%
of the elements.Example 1:
Input: arr = [1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3]
Output: 2.00000
Approach
Java
import java.util.Arrays;public class MeanOfArray {public static void main(String[] args) {int[] arr = { 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,2, 2, 2, 2, 2, 2, 2, 2, 3 };System.out.println(trimMean(arr));}static double trimMean(int[] arr) {int n = arr.length;int x = 5 * n / 100;double ans = 0;Arrays.sort(arr);for (int i = x; i < n - x; i++)ans += arr[i];return ans / (n - 2 * x);}}
C++
#include <bits/stdc++.h>using namespace std;double trimMean(vector<int> &arr){int n = arr.size();int x = 5 * n / 100;double ans = 0;sort(arr.begin(), arr.end());for (int i = x; i < n - x; i++)ans += arr[i];return ans / (n - 2 * x);}int main(){vector<int> arr = {1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,2, 2, 2, 2, 2, 2, 2, 2, 3};cout << trimMean(arr);return 0;}
No comments:
Post a Comment