초보코딩
LeetCode - 1480. Running Sum of 1d Array
07514673
2021. 8. 5. 15:23
Problem
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] |
Solution
class Solution: def runningSum(self, nums: List[int]) -> List[int]: for i in range(1, len(nums)): nums[i] = nums[i-1] + nums[i] return nums |
두번째 문제
역시 문제를 처음보면 말문이 막힐 정도로 어려웠다.
오늘도 물론 해결책을 봐야 해결할 수 있었다.
for i in range는 지난 번 문제를 통해 이해 할 수있었다. 이번엔 숫자 1부터 입력되는 배열 nums의 길이 만큼 반복되는 조건이다. 그렇다면 nums[i] = nums[i-1] + nums[i]는 어떻게 해석 할것인가.
nums[1] = nums[1-1] + nums[1] > 1 = 0 + 1
nums[2] = nums[2-1] + nums[2] > 3 = 1 + 2
nums[3] = nums[3-1] + nums[3] > 6 = 3 + 3 /* 앞에 3은 위에 nums[2]가 '3'으로 변경 된 것이다.
nums[4] = nums[4-1] + nums[4] > 10 =6 + 4 /* 앞에 6은 위에 nums[3]가 '6'으로 변경 된 것이다.
[1, 2, 3, 4] 1번째 for문
[1, 3, 3, 4] 2번째 for문
[1, 3, 6, 4] 3번째 for문
[1, 3, 6, 10] 4번째 for문
[Output] [1,3,6,10]