[LeetCode] Mean of Array After Removing Some Element

아르당·2026년 6월 4일

LeetCode

목록 보기
340/584
post-thumbnail

문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음

Problem

정수 배열 arr이 주어졌을 때, 가장 작은 5%과 가장 큰 5% 요소를 제거한 후 남은 정수의 평균을 구해라.

답과 차이가 10^-5 이내인 것은 정답으로 간주된다.

Example

#1
Input: arr = [1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3]
Output: 2.00000
Explanation: 배열의 최솟값과 최댓값을 제거하면, 모든 요소가 2가 되어서 평균은 2이다.

#2
Input: arr = [6, 2, 7, 5, 1, 2, 0, 3, 10, 2, 5, 0, 5, 5, 0, 8, 7, 6, 8, 0]
Output: 4.00000

#3
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

Constraints

  • 20 <= arr.length <= 1000
  • arr.length는 20의 배수이다.
  • 0 <= arr[i] <= 10^5

Solved

class Solution {
    public double trimMean(int[] arr) {
        int n = arr.length;
        int offset = 5 * n / 100;
        int start = offset;
        int end = n - offset;
        double total = end - start;
        double sum = 0;

        Arrays.sort(arr);

        for(int i = start; i < end; i++){
            sum += arr[i];
        }

        return sum / total;
    }
}
profile
내 마음대로 코드 작성하는 세상

0개의 댓글