Problema
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.
Vincoli
1 ≤ length ≤ 100,000; -10⁹ ≤ each value ≤ 10⁹
Esempi
Input:
numbers = [2, 4, 6]
Output atteso:
expected = 4.0
Input:
std::vector<long long> numbers = {2, 4, 6};
Output atteso:
double expected = 4.0;
Input:
long[] numbers = new long[] {2, 4, 6};
Output atteso:
double expected = 4.0;
Spiegazione
(2 + 4 + 6) / 3 = 4.
Input:
numbers = [1, 2]
Output atteso:
expected = 1.5
Input:
std::vector<long long> numbers = {1, 2};
Output atteso:
double expected = 1.5;
Input:
long[] numbers = new long[] {1, 2};
Output atteso:
double expected = 1.5;
Spiegazione
(1 + 2) / 2 = 1.5; divide as decimals.
Come affrontarlo
Prova prima da solo, poi apri un suggerimento alla volta.
Suggerimento 1
The average comes from combining the whole list into one total and then using its length.
Suggerimento 2
A single pass can collect the sum, then divide by how many values there are.
Suggerimento 3
Be careful to preserve decimal precision instead of using integer division.
Complessità attesa
O(n) time, O(1) extra space
Riferimenti
Questa sfida è adattata per CodeUtility. Segui la traccia e i vincoli sopra.