728x90
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]
나의 풀이
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
/**
* @param {number[]} nums
* @return {number[]}
*/
var runningSum = function(nums) {
const answer = []
for(let i=0; i<nums.length; i++){
let hap =0
for(let j=0; j<=i; j++){
hap += nums[j]
}
answer.push(hap)
}
return answer
};
|
cs |
문제를 풀며 느낀 점
- 이중 for문에 대해서 조금 어려움을 느꼈었는데 이번 문제를 풀면서 조금 도움이 된 것 같습니다. 먼저 배열 nums를 인자로 받았고 for문을 통해서 i를 nums.length보다 작은 만큼 순회합니다. 그 안에 for문을 통해서 hap을 0으로 초기화해주고 j는 0부터 i보다 작을 때까지 증가시킨 후 hap 에 num[j]번째 있는 value를 더한 값을 answer에 각각 push 해줍니다.
728x90
'코딩 테스트 풀이 🛠' 카테고리의 다른 글
[프로그래머스] 3진법 뒤집기 (0) | 2023.01.21 |
---|---|
[프로그래머스] 최대공약수와 최소공배수 (0) | 2023.01.21 |
[Leet Code - eazy] 2535. Difference Between Element Sum and Digit Sum of an Array (0) | 2023.01.21 |
[Leet Code - eazy] 2011. Final Value of Variable After Performing Operations (0) | 2023.01.21 |
[Leet Code - eazy] 1108. Defanging an IP Address (0) | 2023.01.21 |