目录
- 题目要求
- 思路:模拟
- Java
- C++
- Rust
题目要求


思路:模拟
- 根据题意模拟即可:
- 排序然后只取中间符合条件的数加和然后计算均值;
- 根据给出的数组长度n为20的倍数,5%可直接取n/20;
- 两边各去除5%,则剩余长度为0.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(n log n),为排序复杂度,构造答案复杂度为O(n)
- 空间复杂度: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(n log n),为排序复杂度,构造答案复杂度为O(n)
- 空间复杂度: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(n log n),为排序复杂度,构造答案复杂度为O(n)
- 空间复杂度:O(log n),为排序复杂度
以上就是Java C++ 题解leetcode1619删除某些元素后数组均值的详细内容,更多关于Java C++ 删除元素后数组均值的资料请关注其它相关文章!
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

评论(0)