Đề bài
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.
Ràng buộc
1 ≤ length ≤ 100,000; -10⁹ ≤ each value ≤ 10⁹
Ví dụ
Đầu vào:
numbers = [2, 4, 6]
Kết quả mong đợi:
expected = 4.0
Đầu vào:
std::vector<long long> numbers = {2, 4, 6};
Kết quả mong đợi:
double expected = 4.0;
Đầu vào:
long[] numbers = new long[] {2, 4, 6};
Kết quả mong đợi:
double expected = 4.0;
Giải thích
(2 + 4 + 6) / 3 = 4.
Đầu vào:
numbers = [1, 2]
Kết quả mong đợi:
expected = 1.5
Đầu vào:
std::vector<long long> numbers = {1, 2};
Kết quả mong đợi:
double expected = 1.5;
Đầu vào:
long[] numbers = new long[] {1, 2};
Kết quả mong đợi:
double expected = 1.5;
Giải thích
(1 + 2) / 2 = 1.5; divide as decimals.
Hướng tiếp cận
Hãy tự thử trước, sau đó mở từng gợi ý một.
Gợi ý 1
The average comes from combining the whole list into one total and then using its length.
Gợi ý 2
A single pass can collect the sum, then divide by how many values there are.
Gợi ý 3
Be careful to preserve decimal precision instead of using integer division.
Độ phức tạp mong đợi
O(n) time, O(1) extra space
Tham khảo
Thử thách này đã được điều chỉnh cho CodeUtility. Hãy làm theo đề bài và các ràng buộc ở trên.