亲宝软件园·资讯

展开

Java C++ 删除元素后数组均值

AnjaVon 人气:0

题目要求

思路:模拟

Java

class Solution {
    public double trimMean(int[] arr) {
        Arrays.sort(arr);
        int n = arr.length, tot = 0;
        for (int i = n / 20; i < n - n / 20; i++)
            tot += arr[i];
        return tot / (n * 0.9);
    }
}

C++

class Solution {
public:
    double trimMean(vector<int>& arr) {
        sort(arr.begin(), arr.end());
        int n = arr.size(), tot = 0;
        for (int i = n / 20; i < n - n / 20; i++)
            tot += arr[i];
        return tot / (n * 0.9);
    }
};

Rust

impl Solution {
    pub fn trim_mean(arr: Vec<i32>) -> f64 {
        let mut res = arr.clone();
        let n = arr.len();        
        res.sort();
        res[(n / 20)..(n - n / 20)].iter().sum::<i32>() as f64 / (n as f64 * 0.9)
    }
}

加载全部内容

相关教程
猜你喜欢
用户评论