Skip to content

Commit

Permalink
O(n) nth_element
Browse files Browse the repository at this point in the history
  • Loading branch information
keineahnung2345 authored Oct 25, 2020
1 parent 906416f commit c392edc
Showing 1 changed file with 22 additions and 0 deletions.
22 changes: 22 additions & 0 deletions 1619. Mean of Array After Removing Some Elements.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,25 @@ class Solution {
return (double)accumulate(arr.begin()+rem, arr.end()-rem, 0)/(n-2*rem);
}
};

//O(n) nth_element
//https://leetcode.com/problems/mean-of-array-after-removing-some-elements/discuss/900529/C%2B%2B-O(n)-nth_element
//Runtime: 20 ms, faster than 45.74% of C++ online submissions for Mean of Array After Removing Some Elements.
//Memory Usage: 9.8 MB, less than 99.83% of C++ online submissions for Mean of Array After Removing Some Elements.
class Solution {
public:
double trimMean(vector<int>& arr) {
int n = arr.size();

int rem = n*5.0/100;

//[rem, n-rem*2, rem]

//put the first "rem" elements at their right place
nth_element(arr.begin(), arr.begin()+rem, arr.end());
//put the second part(n-rem*2 elements) at their right place
nth_element(arr.begin()+rem, arr.end()-rem, arr.end());

return accumulate(arr.begin()+rem, arr.end()-rem, 0)/(double)(n-rem*2);
}
};

0 comments on commit c392edc

Please sign in to comment.