|
| 1 | +/** |
| 2 | + * [1619] Mean of Array After Removing Some Elements |
| 3 | + * |
| 4 | + * Given an integer array arr, return the mean of the remaining integers after removing the smallest 5% and the largest 5% of the elements. |
| 5 | + * Answers within 10^-5 of the actual answer will be considered accepted. |
| 6 | + * |
| 7 | + * Example 1: |
| 8 | + * |
| 9 | + * Input: arr = [1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3] |
| 10 | + * Output: 2.00000 |
| 11 | + * Explanation: After erasing the minimum and the maximum values of this array, all elements are equal to 2, so the mean is 2. |
| 12 | + * |
| 13 | + * Example 2: |
| 14 | + * |
| 15 | + * Input: arr = [6,2,7,5,1,2,0,3,10,2,5,0,5,5,0,8,7,6,8,0] |
| 16 | + * Output: 4.00000 |
| 17 | + * |
| 18 | + * Example 3: |
| 19 | + * |
| 20 | + * Input: arr = [6,0,7,0,7,5,7,8,3,4,0,7,8,1,6,8,1,1,2,4,8,1,9,5,4,3,8,5,10,8,6,6,1,0,6,10,8,2,3,4] |
| 21 | + * Output: 4.77778 |
| 22 | + * |
| 23 | + * |
| 24 | + * Constraints: |
| 25 | + * |
| 26 | + * 20 <= arr.length <= 1000 |
| 27 | + * arr.length is a multiple of 20. |
| 28 | + * <font face="monospace">0 <= arr[i] <= 10^5</font> |
| 29 | + * |
| 30 | + */ |
| 31 | +pub struct Solution {} |
| 32 | + |
| 33 | +// problem: https://leetcode.com/problems/mean-of-array-after-removing-some-elements/ |
| 34 | +// discuss: https://leetcode.com/problems/mean-of-array-after-removing-some-elements/discuss/?currentPage=1&orderBy=most_votes&query= |
| 35 | + |
| 36 | +// submission codes start here |
| 37 | + |
| 38 | +impl Solution { |
| 39 | + pub fn trim_mean(arr: Vec<i32>) -> f64 { |
| 40 | + let mut arr = arr; |
| 41 | + |
| 42 | + arr.sort_unstable(); |
| 43 | + |
| 44 | + let cut = arr.len() / 20; |
| 45 | + |
| 46 | + arr[cut..arr.len() - cut].iter().sum::<i32>() as f64 / (arr.len() - 2 * cut) as f64 |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +// submission codes end |
| 51 | + |
| 52 | +#[cfg(test)] |
| 53 | +mod tests { |
| 54 | + use super::*; |
| 55 | + |
| 56 | + #[test] |
| 57 | + fn test_1619_example_1() { |
| 58 | + let arr = vec![1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3]; |
| 59 | + |
| 60 | + let result = 2.00000; |
| 61 | + |
| 62 | + assert_f64_near!(Solution::trim_mean(arr), result); |
| 63 | + } |
| 64 | + |
| 65 | + #[test] |
| 66 | + fn test_1619_example_2() { |
| 67 | + let arr = vec![6, 2, 7, 5, 1, 2, 0, 3, 10, 2, 5, 0, 5, 5, 0, 8, 7, 6, 8, 0]; |
| 68 | + |
| 69 | + let result = 4.00000; |
| 70 | + |
| 71 | + assert_f64_near!(Solution::trim_mean(arr), result); |
| 72 | + } |
| 73 | + |
| 74 | + #[test] |
| 75 | + fn test_1619_example_3() { |
| 76 | + let arr = vec![ |
| 77 | + 6, 0, 7, 0, 7, 5, 7, 8, 3, 4, 0, 7, 8, 1, 6, 8, 1, 1, 2, 4, 8, 1, 9, 5, 4, 3, 8, 5, 10, |
| 78 | + 8, 6, 6, 1, 0, 6, 10, 8, 2, 3, 4, |
| 79 | + ]; |
| 80 | + |
| 81 | + let result = 4.777777777777778; |
| 82 | + |
| 83 | + assert_f64_near!(Solution::trim_mean(arr), result); |
| 84 | + } |
| 85 | +} |
0 commit comments