当前位置:网站首页>Force buckle 2_ 1480. Dynamic sum of one-dimensional array

Force buckle 2_ 1480. Dynamic sum of one-dimensional array

2022-07-04 22:11:00 Don't sleep in class

Give you an array nums . Array 「 Dynamic and 」 The calculation formula of is :runningSum[i] = sum(nums[0]…nums[i]) .

Please return nums Dynamic and .

Example 1:

 Input :nums = [1,2,3,4]
 Output :[1,3,6,10]
 explain : The dynamic and computational process is  [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]
 explain : The dynamic and computational process is  [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]

source : Power button (LeetCode)

Java solution

class Solution {
    
    public int[] runningSum(int[] nums) {
    
        int n = nums.length;
        for (int i = 1; i < n; i++) {
    
            nums[i] += nums[i - 1];
            // Each bit from the second is the accumulation of the front 
        }
        return nums;
    }
}

Python solution ( Thinking and Java In the same )

class Solution:
    def runningSum(self, nums: List[int]) -> List[int]:
        n = len(nums)
        for i in range(1, n):
            nums[i] += nums[i - 1]
        return nums
原网站

版权声明
本文为[Don't sleep in class]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/185/202207042138559272.html