모든 챌린지
쉬움 1명 해결 정답률 100.0%

Median of a List

Find the middle value of a list after sorting.

배우게 될 내용

  • Sort a list and find its middle
  • Handle even and odd lengths
  • Average the two middle values

문제

번역본 보기

Sort the values into ascending order. For an odd number of values, take the middle one. For an even number, take the arithmetic mean of the two middle values. This challenge accepts only nonempty lists.

Implement median_number(numbers).

Input

numbers: The nonempty list of values.

Output

Return the median as a number; it may end in .5.

제약 조건

1 ≤ list length ≤ 100,000. Each value is an integer between −1,000,000,000 and 1,000,000,000.

예시

예시 1
입력:
numbers = [2, 8, 4, 10]

예상 출력:
expected = 6.0
입력:
std::vector<long long> numbers = {2, 8, 4, 10};

예상 출력:
double expected = 6.0;
입력:
long[] numbers = new long[] {2, 8, 4, 10};

예상 출력:
double expected = 6.0;

설명

Sorted order is 2, 4, 8, 10. The middle pair averages to (4 + 8) / 2 = 6.

예시 2
입력:
numbers = [9, 1, 4]

예상 출력:
expected = 4.0
입력:
std::vector<long long> numbers = {9, 1, 4};

예상 출력:
double expected = 4.0;
입력:
long[] numbers = new long[] {9, 1, 4};

예상 출력:
double expected = 4.0;

설명

Sorted order is 1, 4, 9, whose middle value is 4.

접근 방법

먼저 스스로 풀어 본 뒤 힌트를 하나씩 열어 보세요.

힌트 1

The median depends on sorted order, so the positions in the sorted list are what matter.

힌트 2

After sorting, use the middle element for odd length, or combine the two middle elements for even length.

힌트 3

Be careful to preserve halves when averaging two middle values, since the answer may end in .5.

예상 복잡도

O(n log n) time, O(n) extra space

참고 자료

이 문제는 CodeUtility에 맞게 수정되었습니다. 위의 설명과 제약 조건을 기준으로 풀어 주세요.

코더마다 가장 좋은 통과 풀이입니다. 더 빠르고, 메모리를 덜 쓰고, 평가가 좋은 풀이가 위에 옵니다.

# 코더 언어 시간 메모리 AI 평가 풀이
1 RCRiccardo Corti Python 848 ms - 3/5 코드 보기

다른 사람의 풀이 보기

커뮤니티 풀이

스포일러: 아래에 전체 풀이 1개가 있습니다 먼저 직접 풀어보세요. 다른 개발자의 코드와 AI 리뷰도 참고할 수 있습니다. 로그인하고 문제를 풀면 토론에 참여할 수 있습니다.