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

Sum an Array

Add up all values in a list.

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

  • Loop over every element of a list
  • Keep a running total
  • Handle an empty list

โจทย์

ดูฉบับแปล

Return the total of all numbers in the list. An empty list sums to 0.

Implement sum_array(numbers).

Input

numbers: The list of integers.

Output

Return the sum.

เงื่อนไข

0 ≤ length ≤ 100,000; the total fits in a 64-bit integer

ตัวอย่าง

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

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

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

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

คำอธิบาย

1 + 2 + 3 + 4 = 10.

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

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

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

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

คำอธิบาย

Nothing to add: 0.

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

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

คำใบ้ 1

Add every element as you traverse the list once.

คำใบ้ 2

Keep a running total instead of building anything extra.

คำใบ้ 3

An empty list should stay at 0, so the initial total matters.

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

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

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

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

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

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

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

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

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