본문 바로가기

알아가는 중/코딩테스트 | 알고리즘

Leetcode 1480

1480. Running Sum of 1d Array

https://leetcode.com/problems/running-sum-of-1d-array/

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].
class Solution(object):
    def runningSum(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        for i in range(1, len(nums)):
            nums[i] += nums[i-1]
        return nums

Constraints:

  • 1 <= nums.length <= 1000
  • -10^6 <= nums[i] <= 10^6

고려할 것; edge case !

nums.length = 0인 경우. 근데 constraints 에서 1 이상이라고 줬다.

input으로 들어온 데이터를 바로 수정하는 건 별로 좋은 코드는 아닌 것 같다. 데이터가 꼬일 수도 있고, 이게 어떤 영향을 미칠지 모르니까.