Java&C++题解与拓展——leetcode1619.删除某些元素后的数组均值【么的新知识】

821 阅读1分钟
每日一题做题记录,参考官方和三叶的题解

题目要求

image.png

image.png

思路:模拟

  • 根据题意模拟即可:
    • 排序然后只取中间符合条件的数加和然后计算均值;
    • 根据给出的数组长度nn2020的倍数,5%5\%可直接取n/20n/20
    • 两边各去除5%5\%,则剩余长度为0.9n0.9n

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);
    }
}
  • 时间复杂度:O(nlogn)O(n\log n),为排序复杂度,构造答案复杂度为O(n)O(n)
  • 空间复杂度:O(logn)O(\log n),为排序复杂度

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);
    }
};
  • 时间复杂度:O(nlogn)O(n\log n),为排序复杂度,构造答案复杂度为O(n)O(n)
  • 空间复杂度:O(logn)O(\log n),为排序复杂度

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)
    }
}
  • 时间复杂度:O(nlogn)O(n\log n),为排序复杂度,构造答案复杂度为O(n)O(n)
  • 空间复杂度:O(logn)O(\log n),为排序复杂度

总结

快乐模拟、不需要费脑子~

开启认真摸鱼的一天~


欢迎指正与讨论!