Skip to content

Latest commit

 

History

History
49 lines (42 loc) · 1.03 KB

1619.删除某些元素后的数组均值.md

File metadata and controls

49 lines (42 loc) · 1.03 KB

1619.删除某些元素后的数组均值

/*
 * @lc app=leetcode.cn id=1619 lang=typescript
 *
 * [1619] 删除某些元素后的数组均值
 */

// @lc code=start
function trimMean(arr: number[]): number {}
// @lc code=end

解法 1: 模拟

function trimMean(arr: number[]): number {
  const n = arr.length,
    d = n / 20
  arr.sort((a, b) => a - b)
  let sum = 0
  for (let i = d; i < n - d; i++) {
    sum += arr[i]
  }

  return sum / (n - 2 * d)
}

Case

test.each([
  { input: { arr: [1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3] }, output: 2.0 },
  { input: { arr: [6, 2, 7, 5, 1, 2, 0, 3, 10, 2, 5, 0, 5, 5, 0, 8, 7, 6, 8, 0] }, output: 4.0 },
  {
    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,
      ],
    },
    output: 4.77778,
  },
])('input: arr = $input.arr', ({ input: { arr }, output }) => {
  expect(Math.abs(trimMean(arr) - output) <= 10 ** -5).toEqual(true)
})