โจทย์
Build a running sum: the value at position i is the sum of all numbers from position 0 through i.
Implement running_sum(numbers).
Input
numbers: The list of integers.
Output
Return the list of running totals.
เงื่อนไข
0 ≤ length ≤ 100,000; totals fit in a 64-bit integer
ตัวอย่าง
อินพุต:
numbers = [1, 2, 3, 4]
ผลลัพธ์ที่คาดหวัง:
expected = [1, 3, 6, 10]
อินพุต:
std::vector<long long> numbers = {1, 2, 3, 4};
ผลลัพธ์ที่คาดหวัง:
std::vector<long long> expected = {1, 3, 6, 10};
อินพุต:
long[] numbers = new long[] {1, 2, 3, 4};
ผลลัพธ์ที่คาดหวัง:
long[] expected = new long[] {1, 3, 6, 10};
คำอธิบาย
Totals so far: 1, 1+2=3, 3+3=6, 6+4=10.
อินพุต:
numbers = [5, -5, 5]
ผลลัพธ์ที่คาดหวัง:
expected = [5, 0, 5]
อินพุต:
std::vector<long long> numbers = {5, -5, 5};
ผลลัพธ์ที่คาดหวัง:
std::vector<long long> expected = {5, 0, 5};
อินพุต:
long[] numbers = new long[] {5, -5, 5};
ผลลัพธ์ที่คาดหวัง:
long[] expected = new long[] {5, 0, 5};
คำอธิบาย
Totals: 5, 0, 5.
แนวทางการแก้
ลองทำเองก่อน แล้วค่อยเปิดคำใบ้ทีละข้อ
คำใบ้ 1
แต่ละค่าผลลัพธ์ขึ้นกับผลรวมของค่าก่อนหน้าทั้งหมดรวมกับค่าปัจจุบัน
คำใบ้ 2
เก็บผลรวมสะสมไว้ขณะไล่ผ่านรายการ
คำใบ้ 3
ตำแหน่งแรกควรเท่ากับค่าตัวแรกของอินพุตพอดี
ความซับซ้อนที่คาดหวัง
เวลา O(n), หน่วยความจำเพิ่ม O(n)
แหล่งอ้างอิง
โจทย์นี้ปรับให้เหมาะกับ CodeUtility กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน