ง่าย 0 ข้อที่แก้แล้ว อัตราผ่าน 0%

Array Average

Compute the average of a list of numbers.

สิ่งที่คุณจะได้เรียนรู้

  • Sum values and divide by the count
  • Return a decimal result
  • Avoid integer division mistakes

โจทย์

ดูฉบับแปล

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.

เงื่อนไข

1 ≤ length ≤ 100,000; -10⁹ ≤ each value ≤ 10⁹

ตัวอย่าง

ตัวอย่างที่ 1
อินพุต:
numbers = [2, 4, 6]

ผลลัพธ์ที่คาดหวัง:
expected = 4.0
อินพุต:
std::vector<long long> numbers = {2, 4, 6};

ผลลัพธ์ที่คาดหวัง:
double expected = 4.0;
อินพุต:
long[] numbers = new long[] {2, 4, 6};

ผลลัพธ์ที่คาดหวัง:
double expected = 4.0;

คำอธิบาย

(2 + 4 + 6) / 3 = 4.

ตัวอย่างที่ 2
อินพุต:
numbers = [1, 2]

ผลลัพธ์ที่คาดหวัง:
expected = 1.5
อินพุต:
std::vector<long long> numbers = {1, 2};

ผลลัพธ์ที่คาดหวัง:
double expected = 1.5;
อินพุต:
long[] numbers = new long[] {1, 2};

ผลลัพธ์ที่คาดหวัง:
double expected = 1.5;

คำอธิบาย

(1 + 2) / 2 = 1.5; divide as decimals.

แนวทางการแก้

ลองทำเองก่อน แล้วค่อยเปิดคำใบ้ทีละข้อ

คำใบ้ 1

The average comes from combining the whole list into one total and then using its length.

คำใบ้ 2

A single pass can collect the sum, then divide by how many values there are.

คำใบ้ 3

Be careful to preserve decimal precision instead of using integer division.

ความซับซ้อนที่คาดหวัง

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

แหล่งอ้างอิง

โจทย์นี้ปรับให้เหมาะกับ CodeUtility กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน

คำตอบที่ผ่านดีที่สุดของแต่ละคน คำตอบที่เร็วกว่า ใช้หน่วยความจำน้อยกว่า และได้คะแนนดีกว่าจะอยู่ด้านบน

ยังไม่มีคำตอบที่ผ่าน แก้โจทย์นี้แล้วคว้าอันดับหนึ่งไปเลย

เรียนรู้จากคนอื่น

แนวทางจากชุมชน

ยังไม่มีวิธีทำที่เผยแพร่ ลองแก้โจทย์นี้เพื่อแชร์วิธีแรก