给你一个整数数组 salary
,数组里每个数都是 唯一 的,其中 salary[i]
是第 i
个员工的工资。
请你返回去掉最低工资和最高工资以后,剩下员工工资的平均值。
示例 1:
输入:salary = [4000,3000,1000,2000] 输出:2500.00000 解释:最低工资和最高工资分别是 1000 和 4000 。 去掉最低工资和最高工资以后的平均工资是 (2000+3000)/2= 2500
示例 2:
输入:salary = [1000,2000,3000] 输出:2000.00000 解释:最低工资和最高工资分别是 1000 和 3000 。 去掉最低工资和最高工资以后的平均工资是 (2000)/1= 2000
示例 3:
输入:salary = [6000,5000,4000,3000,2000,1000] 输出:3500.00000
示例 4:
输入:salary = [8000,9000,2000,3000,6000,1000] 输出:4750.00000
提示:
3 <= salary.length <= 100
10^3 <= salary[i] <= 10^6
salary[i]
是唯一的。- 与真实值误差在
10^-5
以内的结果都将视为正确答案。
方法一:模拟
按题意模拟即可。
遍历数组,求出最大值和最小值,并且累加和,然后求出去掉最大值和最小值后的平均值。
时间复杂度 salary
的长度。
class Solution:
def average(self, salary: List[int]) -> float:
s = sum(salary) - min(salary) - max(salary)
return s / (len(salary) - 2)
class Solution {
public double average(int[] salary) {
int s = 0;
int mi = 10000000, mx = 0;
for (int v : salary) {
mi = Math.min(mi, v);
mx = Math.max(mx, v);
s += v;
}
s -= (mi + mx);
return s * 1.0 / (salary.length - 2);
}
}
class Solution {
public:
double average(vector<int>& salary) {
int s = 0;
int mi = 1e7, mx = 0;
for (int v : salary) {
s += v;
mi = min(mi, v);
mx = max(mx, v);
}
s -= (mi + mx);
return (double) s / (salary.size() - 2);
}
};
func average(salary []int) float64 {
s := 0
mi, mx := 10000000, 0
for _, v := range salary {
s += v
mi = min(mi, v)
mx = max(mx, v)
}
s -= (mi + mx)
return float64(s) / float64(len(salary)-2)
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
function average(salary: number[]): number {
let max = -Infinity;
let min = Infinity;
let sum = 0;
for (const v of salary) {
sum += v;
max = Math.max(max, v);
min = Math.min(min, v);
}
return (sum - max - min) / (salary.length - 2);
}
impl Solution {
pub fn average(salary: Vec<i32>) -> f64 {
let n = salary.len() as i32;
let mut min = i32::MAX;
let mut max = i32::MIN;
let mut sum = 0;
for &num in salary.iter() {
min = min.min(num);
max = max.max(num);
sum += num;
}
f64::from(sum - min - max) / f64::from(n - 2)
}
}
#define max(a,b) (((a) > (b)) ? (a) : (b))
#define min(a,b) (((a) < (b)) ? (a) : (b))
double average(int* salary, int salarySize) {
int ma = INT_MIN;
int mi = INT_MAX;
int sum = 0;
for (int i = 0 ; i < salarySize; i++) {
sum += salary[i];
ma = max(ma, salary[i]);
mi = min(mi, salary[i]);
}
return (sum - mi - ma) * 1.0 / (salarySize - 2);
}