Java C++ 題解leetcode1619刪除某些元素后數(shù)組均值
更新時間:2022年09月14日 10:41:45 作者:AnjaVon
這篇文章主要為大家介紹了Java C++ 題解leetcode1619刪除某些元素后數(shù)組均值示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
題目要求


思路:模擬
- 根據(jù)題意模擬即可:
- 排序然后只取中間符合條件的數(shù)加和然后計算均值;
- 根據(jù)給出的數(shù)組長度n為20的倍數(shù),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);
}
}
- 時間復(fù)雜度:O(n log? n),為排序復(fù)雜度,構(gòu)造答案復(fù)雜度為O(n)
- 空間復(fù)雜度:O(log? n),為排序復(fù)雜度
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);
}
};
- 時間復(fù)雜度:O(n log n),為排序復(fù)雜度,構(gòu)造答案復(fù)雜度為O(n)
- 空間復(fù)雜度:O(log? n),為排序復(fù)雜度
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)
}
}
- 時間復(fù)雜度:O(n log ?n),為排序復(fù)雜度,構(gòu)造答案復(fù)雜度為O(n)
- 空間復(fù)雜度:O(log? n),為排序復(fù)雜度
以上就是Java C++ 題解leetcode1619刪除某些元素后數(shù)組均值的詳細(xì)內(nèi)容,更多關(guān)于Java C++ 刪除元素后數(shù)組均值的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
C++實現(xiàn)LeetCode(126.詞語階梯之二)
這篇文章主要介紹了C++實現(xiàn)LeetCode(126.詞語階梯之二),本篇文章通過簡要的案例,講解了該項技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-07-07
C語言之棧和堆(Stack && Heap)的優(yōu)缺點及其使用區(qū)別
本篇文章主要介紹了什么是棧(Stack) 、什么是堆( Heap),以及棧和堆的優(yōu)缺點,同時介紹了應(yīng)該什么時候使用堆和棧,有需要的朋友可以參考下2015-07-07

