Problème
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.
Contraintes
1 ≤ list length ≤ 100,000. Each value is an integer between −1,000,000,000 and 1,000,000,000.
Exemples
Entrée :
numbers = [2, 8, 4, 10]
Sortie attendue :
expected = 6.0
Entrée :
std::vector<long long> numbers = {2, 8, 4, 10};
Sortie attendue :
double expected = 6.0;
Entrée :
long[] numbers = new long[] {2, 8, 4, 10};
Sortie attendue :
double expected = 6.0;
Explication
Sorted order is 2, 4, 8, 10. The middle pair averages to (4 + 8) / 2 = 6.
Entrée :
numbers = [9, 1, 4]
Sortie attendue :
expected = 4.0
Entrée :
std::vector<long long> numbers = {9, 1, 4};
Sortie attendue :
double expected = 4.0;
Entrée :
long[] numbers = new long[] {9, 1, 4};
Sortie attendue :
double expected = 4.0;
Explication
Sorted order is 1, 4, 9, whose middle value is 4.
Comment l'aborder
Essayez d'abord seul, puis ouvrez les indices un par un.
Indice 1
The median depends on sorted order, so the positions in the sorted list are what matter.
Indice 2
After sorting, use the middle element for odd length, or combine the two middle elements for even length.
Indice 3
Be careful to preserve halves when averaging two middle values, since the answer may end in .5.
Complexité attendue
O(n log n) time, O(n) extra space
Références
Ce défi a été adapté pour CodeUtility. Suivez l'énoncé et les contraintes ci-dessus.