当前位置:网站首页>1D Array Dynamics and Question Answers

1D Array Dynamics and Question Answers

2022-08-10 19:57:00 Small question mark we are friends

Given the stem:

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

Please return the dynamic sum of nums.

Title source:

LeetCode


1. Example

The code is as follows (example):

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

2. Answers and NotesRemember

The code is as follows (Java):

class Solution {public int[] runningSum(int[] nums) {int len ​​= nums.length;//Solution 1//create an empty arrayint[] resSum = new int[len];// Traverse the given array, the first element of the array is directly put into the new array, and the subsequent elements are added to the previous element of the new array each time.for(int i = 0; i < len; i++) {if(i == 0) {resSum[i] = nums[i];}else {resSum[i] = resSum[i - 1] + nums[i];}}return resSum;//Solution 2//On the basis of the original array, in-situ traversal and modification are performed, the first element is not modified, and the subsequent elements are added to the previous element each time.for(int i = 0; i < len; i++) {if(i != 0) {nums[i] += nums[i - 1];}}return nums;}}

Summary

The above is what I want to talk about today. This article introduces the solution to the dynamic sum of one-dimensional arrays. Here is a memo for reference.

原网站

版权声明
本文为[Small question mark we are friends]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/222/202208101902513753.html