# LeetCode 1480 ###### tags: `python`,`LeetCode` >這邊使用Python解題 ## 題目: 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. ## 範例 ### 範例 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]. ``` ### 範例 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]. ``` ### 範例 3: ``` Input: nums = [3,1,2,10,1] Output: [3,4,6,16,17] ``` ## 條件限制 * 1 <= nums.length <= 1000 * -10^6 <= nums[i] <= 10^6 ## 我的解題思路: 這題其實是累加,將每個元素與目前狀態做遞加而已 ``` ans[0] = nums[0] ans[1] = nums[0+1] ans[2] = nums[0+1+2] 1. need to know the current state/position => index 2. iterate to the current position in the nums array ``` ## 程式碼: ``` def runningSum(nums): for i in range(1, len(nums)): nums[i] += nums[i-1] return nums ``` ## 測試 ``` numss = [[1,2,3,4], [1,1,1,1,1], [3,1,2,10,1]] anss = [[1,3,6,10], [1,2,3,4,5], [3,4,6,16,17]] for idx in range(len(numss)): result = None try: result = runningSum(numss[idx]) except Exception as ex: print(ex) if result == anss[idx]: print('case 1: pass') else: print('case 1: failed. your ans is', result, 'expect', anss[idx]) ```