[LeetCode] 1491. Average Salary Excluding the Minimum and Maximum Salary

You are given an array of unique integers salary where salary[i] is the salary of the ith employee.

Return the average salary of employees excluding the minimum and maximum salary. Answers within 10-5 of the actual answer will be accepted.

Example 1:
Input: salary = [4000,3000,1000,2000]
Output: 2500.00000
Explanation: Minimum salary and maximum salary are 1000 and 4000 respectively.
Average salary excluding minimum and maximum salary is (2000+3000) / 2 = 2500

Example 2:
Input: salary = [1000,2000,3000]
Output: 2000.00000
Explanation: Minimum salary and maximum salary are 1000 and 3000 respectively.
Average salary excluding minimum and maximum salary is (2000) / 1 = 2000

Constraints:
3 <= salary.length <= 100
1000 <= salary[i] <= 106
All the integers of salary are unique.

去掉最低工资和最高工资后的工资平均值。

给你一个整数数组 salary ,数组里每个数都是 唯一 的,其中 salary[i] 是第 i 个员工的工资。

请你返回去掉最低工资和最高工资以后,剩下员工工资的平均值。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/average-salary-excluding-the-minimum-and-maximum-salary
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路

这道题思路不难,扫描一遍即可。在扫描的过程中我们找到最大值和最小值,最后在计算平均值的时候记得把最大值和最小值减去即可。

复杂度

时间O(n)
空间O(1)

代码

Java实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public double average(int[] salary) {
double sum = 0.0;
int n = salary.length;
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for (int s : salary) {
min = Math.min(min, s);
max = Math.max(max, s);
sum += s;
}
return (sum - min - max) / (n - 2);
}
}

[LeetCode] 1491. Average Salary Excluding the Minimum and Maximum Salary
https://shurui91.github.io/posts/576839838.html
Author
Aaron Liu
Posted on
February 7, 2022
Licensed under