LeetCode 1491. Average Salary Excluding the Minimum and Maximum Salary
考点 | 难度 |
---|---|
String | Easy |
题目
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.
思路
计算所有数总和的同时保存max
和min
,最后从sum中减去max
和min
,除以总数-2。
答案
public double average(int[] nums) {
int sum=0, min=Integer.MAX_VALUE, max=Integer.MIN_VALUE;
for (int num: nums) {
sum+=num;
if (min>num) min=num;
if (max<num) max=num;
}
sum=sum-min-max;
return (double)sum/(nums.length-2);
}