Problème
Return the arithmetic mean of the list: its sum divided by its length, as a decimal number.
Implement array_average(numbers).
Input
numbers: A non-empty list of integers.
Output
Return the average.
Contraintes
1 ≤ length ≤ 100,000; -10⁹ ≤ each value ≤ 10⁹
Exemples
Entrée :
numbers = [2, 4, 6]
Sortie attendue :
expected = 4.0
Entrée :
std::vector<long long> numbers = {2, 4, 6};
Sortie attendue :
double expected = 4.0;
Entrée :
long[] numbers = new long[] {2, 4, 6};
Sortie attendue :
double expected = 4.0;
Explication
(2 + 4 + 6) / 3 = 4.
Entrée :
numbers = [1, 2]
Sortie attendue :
expected = 1.5
Entrée :
std::vector<long long> numbers = {1, 2};
Sortie attendue :
double expected = 1.5;
Entrée :
long[] numbers = new long[] {1, 2};
Sortie attendue :
double expected = 1.5;
Explication
(1 + 2) / 2 = 1.5; divide as decimals.
Comment l'aborder
Essayez d'abord seul, puis ouvrez les indices un par un.
Indice 1
The average comes from combining the whole list into one total and then using its length.
Indice 2
A single pass can collect the sum, then divide by how many values there are.
Indice 3
Be careful to preserve decimal precision instead of using integer division.
Complexité attendue
O(n) time, O(1) extra space
Références
Ce défi a été adapté pour CodeUtility. Suivez l'énoncé et les contraintes ci-dessus.