-
Notifications
You must be signed in to change notification settings - Fork 0
/
1480. Running Sum of 1d Array
86 lines (51 loc) · 1.76 KB
/
1480. Running Sum of 1d Array
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
Given an array nums. We define a running sum of an array as runningSum[i] = sum(nums[0]…nums[i]).
Return the running sum of nums.
Example 1:
Input: nums = [1,2,3,4]
Output: [1,3,6,10]
Explanation: Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4].
Example 2:
Input: nums = [1,1,1,1,1]
Output: [1,2,3,4,5]
Explanation: Running sum is obtained as follows: [1, 1+1, 1+1+1, 1+1+1+1, 1+1+1+1+1].
Example 3:
Input: nums = [3,1,2,10,1]
Output: [3,4,6,16,17]
Constraints:
1 <= nums.length <= 1000
-10^6 <= nums[i] <= 10^6;write the java code, transfer the question to chinese, and explain the code line by line in chinese
给定一个数组 nums。我们定义数组的运行总和为 runningSum[i] = sum(nums[0]…nums[i])。
返回 nums 的运行总和。
示例 1:
输入:nums = [1,2,3,4]
输出:[1,3,6,10]
说明:运行总和如下获得:[1, 1+2, 1+2+3, 1+2+3+4]。
示例 2:
输入:nums = [1,1,1,1,1]
输出:[1,2,3,4,5]
说明:运行总和如下获得:[1, 1+1, 1+1+1, 1+1+1+1, 1+1+1+1+1]。
示例 3:
输入:nums = [3,1,2,10,1]
输出:[3,4,6,16,17]
限制:
1 <= nums.length <= 1000
-10^6 <= nums[i] <= 10^6
以下是 Java 代码:
class Solution {
public int[] runningSum(int[] nums) {
int[] res = new int[nums.length];
int sum = 0;
for (int i = 0; i < nums.length; i++) {
sum += nums[i];
res[i] = sum;
}
return res;
}
}
以下是代码解释:
第 2 行:声明一个数组 res,用于存储结果。
第 3 行:声明一个变量 sum,用于记录当前的总和。
第 4 行:使用循环遍历数组 nums。
第 5 行:累加当前的数字。
第 6 行:将当前的总和存储在结果数组的相应位置。
第 8 行:返回结果数组。