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 class Solution { 2 public double average(int[] salary) { 3 double total = 0.0; 4 int min = (int) Math.pow(10, 6); 5 int max = 1000; 6 for (int s : salary) { 7 if (s < min) { 8 min = s; 9 } 10 if (s > max) { 11 max = s; 12 } 13 total += s; 14 } 15 return (total - max - min) / (salary.length - 2); 16 } 17 }