Leikou 1480- the dynamic sum of one-dimensional array (it takes 0 seconds)

topic:

Give you an array of nums. The calculation formula of the "dynamic sum" of the array is: runningSum[i] = sum(nums[0]…nums[i]).

Please return the dynamic sum of nums.

Example:

Input: nums = [1,2,3,4]
Output: [1,3,6,10]
Explanation: The dynamic and calculation process is [1, 1+2, 1+2+3, 1+2+3+ 4].

Input: nums = [1,1,1,1,1]
Output: [1,2,3,4,5]
Explanation: The dynamic and calculation process is [1, 1+1, 1+1+1, 1+ 1+1+1, 1+1+1+1+1].

Input: nums = [3,1,2,10,1]
Output: [3,4,6,16,17]

Ideas:

Observe that the first one is that the number is always equal to the given array, so just assign a value. Second, the output array is always equal to the previous output array plus the sum of the number corresponding to the original array, so the above can be used Two rules write the results.

Code:

class Solution {
    
    
    public int[] runningSum(int[] nums) {
    
    
            int[] newnum = new int[nums.length];
            newnum[0] = nums[0];

            for (int i = 1; i < nums.length; ++i) {
    
    
                newnum[i] = newnum[i - 1] + nums[i];
            }
        return newnum;
    }
}

effect:

Insert picture description here

I don’t know why the time is 0, I was excited for a long time 233333.

Guess you like

Origin blog.csdn.net/weixin_42898315/article/details/108534274