問題
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 つずつ開いてみましょう。
ヒント 1
Each output element depends on the total of all earlier elements and itself.
ヒント 2
Keep a cumulative total as you move through the list.
ヒント 3
The first position should simply reflect the first input value.
目安の計算量
O(n) time, O(n) extra space
参考資料
この課題はCodeUtility用に調整されています。上記の説明と制約に従ってください。